gpt4 book ai didi

java - 从它的类子类调用对象的方法

转载 作者:行者123 更新时间:2023-12-03 23:35:06 26 4
gpt4 key购买 nike

我正在尝试调用 Weapon 类的方法,它是 Item 的子类。正如您从字段中看到的那样,我已将对象 currentWeapon 声明为 Item 的对象,并且在 setCurrentWeapon 方法中我使用了 getClass() 检查 Item 是否真的是 Weapon 子类的方法。

有没有一种方法可以在我的 Item 对象(实际上是 Weapon 类)上成功调用 Weapon 类的方法?

backpack 是一个包含 Item 对象的 hashmap。如果我在字段中将 currentWeapon 设置为 Weapon,则 Weapon 对象不会添加到 backpack .

编译失败的方法:(找不到符号 - 方法 getMinDamage())

public int attack(Imperial currentEnemy) {
int damage = Utils.random(currentWeapon.getMinDamage(), currentWeapon.getMaxDamage()+1);
currentEnemy.changeHealth(-damage);
return damage;
}

领域:

private Item currentWeapon;

currentWeapon的设置方法:

public boolean setCurrentWeapon(String itemToEquip) {
if(useItem(itemToEquip) == true) {
currentWeapon = backpack.get(itemToEquip.toLowerCase());
if(currentWeapon.getClass() == Weapon.class) {
System.out.println(getNick() + " has equipped " + currentWeapon.getName() + " as current weapon");
equipped = true;
return true;
}
else {
System.out.println(itemToEquip + " is not a weapon");
currentWeapon = null;
return false;
}
}
else System.out.println(itemToEquip + " is not owned by " + getNick());
return false;
}

我希望这个问题不会太令人困惑,请提供有关如何澄清这是否是一个问题的提示

最佳答案

你的问题是当你调用

currentWeapon.getMinDamage()

currentWeapon 的类型为 Item。它的运行时类型是 Weapon,但您会收到一个关于它是错误类型的编译时错误。如果您希望该字段保持 Item 类型,则需要在调用该方法之前将其转换为 Weapon,以告诉编译器您希望它确实是武器类型:

((Weapon)currentWeapon).getMinDamage()

关于java - 从它的类子类调用对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15930995/

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