Reputation: 445
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
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
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
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
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