我试图从类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()

10-08 18:18