我有以下内容:
Public Abstract class Entity
protected int damagePoints = 0;
public getDamagePoints() {
return this.damagePoints;
}
Public abstract class IA extends Entity
Public class Zombie extends IA implements Attacker {
protected int damagePoints = 40;
}
Public class Engineer extends Entity implements DamageReceiver;
Public interface Attacker {
public attack(Entity entity);
}
Public interface DamageReceiver {
public receiveDamage(Attacker entity)
}
Engineer 类重写了此方法:
@Override
public void receiveDamage(Attacker entity) {
if (entity instanceof Zombie) {
int damagePoints = ((Zombie) entity).getDamagePoints();
this.setHealthPoints(this.getHealthPoints() - damagePoints);
}
}
现在我已经实例化了一个工程师和一个僵尸。
当我执行 Zombie.attack(engineer)
时,我在 Engineer 类的 receiveDamage()
中放置了一个断点,我得到 damagePoints
是 0
。
有什么线索可以解释为什么会发生这种情况吗?这是因为我重复了属性 damagePoints
吗?如果是这样,我怎样才能让僵尸拥有 40 点伤害,而无需在所有构造函数中重复 this.damagePoints = 40
?
最佳答案
您重新声明damagePoints
在Zombie
,希望getDamagePoints()
在Entity
将在 Zombie
中获取新值,但正如您所见,事实并非如此。在 Java 中,多态性适用于方法调用,但不适用于变量。 damagePoints
变量 Entity
是 getDamagePoints()
范围内的变量方法,所以0
返回,来自 Entity
的damagePoints
变量。
获取40
返回于 Zombie
,您不需要重新声明另一个同名变量,隐藏 damagePoints
变量 Entity
,但您可以覆盖 getDamagePoints()
Zombie
中的方法。为此,您不需要变量,更不用说同名变量了(除非您计划在游戏过程中更改数量)。在 Zombie
:
@Override
public int getDamagePoints() {
return 40;
}
您甚至可能想要您的getDamagePoints()
方法为abstract
在Entity
,强制子类实现该方法。这意味着变量 damagePoints
在 Entity
中是不必要的.
public abstract int getDamagePoints();
关于java - 获取 Super 的属性值而不是实际对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676083/