java - 获取 Super 的属性值而不是实际对象

标签 java inheritance

我有以下内容:

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() 中放置了一个断点,我得到 damagePoints0

有什么线索可以解释为什么会发生这种情况吗?这是因为我重复了属性 damagePoints 吗?如果是这样,我怎样才能让僵尸拥有 40 点伤害,而无需在所有构造函数中重复 this.damagePoints = 40

enter image description here

最佳答案

您重新声明damagePointsZombie ,希望getDamagePoints()Entity将在 Zombie 中获取新值,但正如您所见,事实并非如此。在 Java 中,多态性适用于方法调用,但不适用于变量。 damagePoints变量 EntitygetDamagePoints() 范围内的变量方法,所以0返回,来自 EntitydamagePoints变量。

获取40返回于 Zombie ,您不需要重新声明另一个同名变量,隐藏 damagePoints变量 Entity ,但您可以覆盖 getDamagePoints() Zombie中的方法。为此,您不需要变量,更不用说同名变量了(除非您计划在游戏过程中更改数量)。在 Zombie :

@Override
public int getDamagePoints() {
   return 40;
}

您甚至可能想要您的getDamagePoints()方法为abstractEntity ,强制子类实现该方法。这意味着变量 damagePointsEntity 中是不必要的.

public abstract int getDamagePoints();

关于java - 获取 Super 的属性值而不是实际对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676083/

相关文章:

c++ - 使重写的虚函数成为非虚函数的目的

java - 正则表达式:如何包含 "if"条件的字符

JAVA 在转换为同级类时避免重复代码

java - 不安全如何重构重复代码

java - ant 属性名称参数是预定义的吗?

c# - 泛型方法继承 : VS and Xamarin Studio yield different results; which is right?

c++ - 继承类为静态

c++ - 何时更喜欢基于模板策略的设计而不是基于非模板继承的设计

java服务包装器父进程挂起

java - 正则表达式用于检查字符串中是否缺少单词模式