所以我正在做一些关于制作小游戏原型(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/