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?
Some points:
Putting this all together, your code should look like this:
public class Creature {
private int protection;
protected Creature() {
}
public Creature(int protection) {
setProtection(protection);
}
public void setProtection(int p) {
if (p < 0)
throw new IllegalArgumentException();
this.protection = p;
}
}
public class Monster extends Creature {
private final int maxProtection;
private Monster(int protection) {
this.maxProtection = protection;
setProtection(protection);
}
@Override
public void setProtection(int p) {
if (protection > maxProtection)
throw new IllegalArgumentException();
super.setProtection(p);;
}
public static Monster create(int protection) {
Monster monster = new Monster(protection);
monster.validate();
return monster;
}
}
You haven't shown what the validate() method dies, but if it's only needed for protection checking, I would delete it and the static factory method and make the constructor of Monster public.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With