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

Java dosen't recognize that object belongs to subclass

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

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

我想要的只是 class ExtraRounds 检查 weapon 是否属于 class RangedWeapon 并据此采取行动,但我没有知道哪里出了问题。感谢任何帮助

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

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

你必须在检查它是否具有该类型后将 state.currentCharacter.weapon 转换为 RangedWeapon:

RangedWeapon rangedWeapon = (RangedWeapon) state.currentCharacter.weapon;
rangedWeapon.rounds +=10;

state.currentCharacter.weaponRangedWeapon 的一个实例,但是它的属性 roundshidden 因为 state.currentCharacter.weapon 属于 Weapon 类型。

要开启 RangedWeapon class 的属性,你必须显式地将其转换为 RangedWeapon class:

RangedWeapon rangedWeapon = ((RangedWeapon) state.currentCharacter.weapon);
rangedWeapon.rounds +=10;

您似乎将 state.currentCharacter.weapon 声明为 Weapon,然后您尝试访问它的 rounds 字段。

在编译阶段,编译器只知道它是Weapon,而Weapon并没有rounds

您可以转换为 RangedWeapon 使其编译:

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