我有以下课程:
public abstract class MyAbstractClass {
protected int x;
protected int number;
public MyAbstractClass(int x) {
this.x = x;
this.number = this.generateNumber();
}
public abstract int generateNumber(); // This class is called in the super constructor and elsewhere
}
public class MySubClass extends MyAbstractClass {
private int y;
public MySubClass(int x, int y) {
super(x);
this.y = y;
}
@Override
public int generateNumber() {
return this.x + this.y; // this.y has not been initialized!
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在运行超级构造函数之前必须初始化MySubClass的y属性,因为使用的方法y。我知道即使有一些偷偷摸摸的解决方法,这也可能是不可能的,但我还没有找到替代解决方案。
另外请记住,我将有更多的派生类,将不同的值传递给它们的构造函数。
您可以将数字计算推迟到需要时为止。
public abstract class MyAbstractClass {
protected int x;
protected Integer number;
public MyAbstractClass(int x) {
this.x = x;
}
public int getNumber() {
if (number == null) {
number = generateNumber();
}
return number.intValue();
}
protected abstract int generateNumber();
}
Run Code Online (Sandbox Code Playgroud)