Java无法识别该对象属于子类

标签 java inheritance abstract-class instanceof

所以我正在做一些关于制作小游戏原型(prototype)的类(class)。我有这些简单的类(以及其他一些不相关的类):

abstract class Weapon {
    int damage;
    int cost; 
}

abstract class RangedWeapon extends Weapon {
    int range;
    int rounds;
}

class ExtraRounds extends Item{
    int cost = 20;
    int uses = 1;
    void use(GameState state){
        if (state.currentCharacter.weapon instanceof RangedWeapon){
            state.currentCharacter.weapon.rounds += 10;
        }
    }

}

但是当尝试编译这个时,我得到了

Implementations.java:56: error: cannot find symbol
            state.currentCharacter.weapon.rounds += 10;
                                         ^
  symbol:   variable rounds
  location: variable weapon of type Weapon

我想要的是类ExtraRounds来检查weapon是否属于RangedWeapon类并采取相应的行动,但我不知道哪里出了问题。感谢任何帮助

最佳答案

你的武器属于武器类别。您必须将其转换为远程武器,以便编译器知道它是远程武器:

if (state.currentCharacter.weapon instanceof RangedWeapon){
   ((RangedWeapon)state.currentCharacter.weapon).rounds += 10;
}

关于Java无法识别该对象属于子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49534658/

相关文章:

Java.io.File.length() 返回 0

java - 使用单选按钮列表创建自定义对话框

C++如何检查两个类是否来自同一个对象

c# - 是否可以在继承类中覆盖抽象父类的嵌套类定义?

c++ - 抽象类和基类是一回事吗?

java - 在 Google Web Toolkit 中使用 jquery 插件?

python - 覆盖 __dir__ 方法的正确方法是什么?

C# 创建一个从继承类构造的类

java - 在java中,内部类可以继承内部类外部类之外定义的抽象类吗?

java - 如何使用 netbeans IDE 7.4 配置 IBM websphere 应用程序服务器 7.0