Java OOP
SHORT ANSWER QUESTIONS
INHERITANCE &
POLYMORPHISM 2
QUESTIONS
1-public
2-private
3-protected
4-overriding
5-@Override
6-super.toString()
7-Polymorphism
8-True
9-superclass
10-True
11-True
12-Object
13-The issue
in the code above is that the datafields in the
superclass Spell are set to private.
So they are not accessible from other classes, even subclasses. The solution is to make them protected
instead of private. See the
alterations in blue below.
Superclass
|
Subclass
|
public
class Spell
{
//only
the datafields are shown
protected
int manaCost;
protected
String name;
}
|
public
class Frost extends Spell
{
private int damage;
//only the toString()
method is shown
public String toString()
{
return name + "(" + damage +
")";
}
}
|
14-When we
want to call a method in the superclass, we can simply put super in front of
it. See the solution in blue.
Superclass
|
Subclass
|
public
class Enemy
{
//only
the damage method is shown
public int damage(int
defense)
{
return damage * attack/defense;
}
}
|
public
class Ghost extends Enemy
{
//only two
methods are shown
@Override
public int damage(int
defense)
{
return 2*damage * attack/defense;
}
public int critDamage(int defense)
{
return super.damage(defense)
* 5;
}
}
|
15-The
@Override (which is optional) forces your IDE to verify if the method below
it is in fact overriding another method.
In this case, it is not because it is named dmg
instead of damage. We need to make the
names match. See the solution in blue.
Superclass
|
Subclass
|
public
class Badguy
{
//this is
the only instance method
//in the class
public int damage(int
defense)
{
return damage * attack/defense;
}
}
|
public
class Boss extends Badguy
{
//only this
method is shown
@Override
public int damage(int defense)
{
return 2*damage * attack/defense;
}
}
|
|