Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java dosen’t recognize that object belongs to subclass without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
So I’m doing some coursework about making a little game’s prototype. I have these simple classes (and some others that are not relevant):
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; } } }
but when trying to compile this I’m getting
Implementations.java:56: error: cannot find symbol state.currentCharacter.weapon.rounds += 10; ^ symbol: variable rounds location: variable weapon of type Weapon
All I want is the class ExtraRounds
to check if the weapon
is of class RangedWeapon
and act accordingly, but I don’t know where things are going wrong. Any help is appreciated
Answer
Your weapon is of a Weapon class. You have to cast it to a RangedWeapon in order to your compiler know it is a RangedWeapon:
if (state.currentCharacter.weapon instanceof RangedWeapon){ ((RangedWeapon)state.currentCharacter.weapon).rounds += 10; }
We are here to answer your question about Java dosen’t recognize that object belongs to subclass - If you find the proper solution, please don't forgot to share this with your team members.