gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:24:10 24 4
gpt4 key购买 nike

我有以下内容:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com