我试图从类Weapon
调用方法,该类是Item
的子类。从字段中可以看到,我已将对象currentWeapon
声明为Item的对象,在setCurrentWeapon
方法中,我使用getClass()
方法来检查Item
确实是武器子类。
有没有一种方法可以成功地从Item对象上的Weapon
类(实际上是Weapon类)中调用方法?backpack
是包含Item
对象的哈希图。如果在字段中将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
类型:((Weapon)currentWeapon).getMinDamage()