我有这个超类Creature及其子类Monster。现在我有一个最终变量被引用而没有被初始化的问题。
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;
}
}
和子类:
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
}
}
如您所见,当我初始化一个 new 时Monster,它会调用Creaturewith的构造函数super(protection)。在 的构造函数中Creature,调用该方法,该方法canHaveAsProtection(p)通过动态绑定获取Monster. 然而,这个被覆盖的版本使用了maxProtection尚未初始化的最终变量......我该如何解决这个问题?