英文:
Java - Setting Class Properties Before Super
问题
我有以下的类:
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(); // 这个方法在超类构造函数和其他地方被调用
}
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尚未被初始化!
}
}
我的问题是MySubClass
的y
属性在超类构造函数运行之前必须被初始化,因为在超类构造函数中会使用y
属性的方法。
我意识到即使使用一些巧妙的方法可能也无法实现这一点,但我尚未找到替代方案。
另外请注意,我将会有更多的派生类,它们的构造函数会传入不同的值。
英文:
I have the follow classes:
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!
}
}
My issue is that MySubClass
's y
property has to be initialized before the super constructor is run, because a method using y
is run in the super constructor.
I am aware that this may not be possible even with some sneaky workaround, but I am yet to find an alternative solution.
Also please keep in mind that I will have many more derived classes, with different values being passed into their constructors.
答案1
得分: 4
你可以将数字计算推迟到需要的时候再进行。
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();
}
英文:
You can defer the number calculation until it is needed.
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论