I have this superclass Creature
and its subclass Monster
. Now I have this problem of a final variable being referenced without it being initialized.
public class Creature {
private int protection;
public Creature(int protection) {
setProtection(protection);
}
public void setProtection(int p) {
if(!canHaveAsProtection(p))
throw new Exception();
this.protection = p;
}
public boolean canHaveAsProtection(int p) {
return p>0;
}
}
and the subclass:
public class Monster extends Creature {
private final int maxProtection;
public Monster(int protection) {
super(protection);
this.maxProtection = protection;
}
@Override
public boolean canHaveAsProtection(int p) {
return p>0 && p<maxProtection
}
}
As you can see, when I initialize a new Monster
, it will call the constructor of Creature
with super(protection)
. In the constructor of Creature
, the method canHaveAsProtection(p)
is called, which by dynamic binding takes the overwritten one in Monster
. However, this overwritten version uses the final variable maxProtection
which hasn't been initialized yet...
How can I solve this?