Java dosen’t recognize that object belongs to subclass

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *