nestor556
nestor556

Reputation: 445

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

Upvotes: 0

Views: 78

Answers (4)

hoan
hoan

Reputation: 1098

state.currentCharacter.weapon is an instance of RangedWeapon, however its attribute rounds is hidden because state.currentCharacter.weapon is under Weapon type.

To turn on the attributes of RangedWeapon class, you have to explicitly cast it to RangedWeapon class:

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

Upvotes: 0

xingbin
xingbin

Reputation: 28269

It seems you declare state.currentCharacter.weapon as Weapon, then you attemp to access its rounds field.

At compile stage, the compiler only know it is Weapon, and Weapon does not hasrounds.

You can cast to RangedWeapon to make it compile:

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

Upvotes: 4

dj_frunza
dj_frunza

Reputation: 1593

You have to cast state.currentCharacter.weapon to RangedWeapon after checking whether it has that type:

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

Upvotes: 0

edu
edu

Reputation: 126

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

Upvotes: 5

Related Questions