基本上,我想做的是强制子类调用抽象超类方法(在子类中实现),所以每次创建新的时都不必显式写它子类。
我在超类的构造函数中写了一次,因为我希望它强制它用于每个实现。
public abstract class SupahClass {
public SupahClass() {
doStuff(); // It IS executed when the subclass constructor is called
init(); // NOT executed, even though it's implemented
}
private void doStuff() { ... }
protected abstract void init();
}
public class SomeSubClass extends SupahClass {
// The problem lies HERE: this is executed AFTER init() ... so it gets NULL again
private TextBox myTextBox = null;
public SomeSubClass() {
super(); // invokes the super constructor, so init() should be called
// I could call init(); here EACH time i create a new subclass... but no :)
}
@Override
public void init() {
this.myTextBox = new TextBox(); // Executed BEFORE its declared as null above
}
}
当然,超类不能真正调用它,因为它是一个抽象(如此未定义)的方法,但它是一个ABSTRACT类,所以它不能实例化,它必须将任务委托给它的子类,所以为什么它们不能调用它摘要但现在实施的方法?
修改
请参阅子类属性myTextBox和init()实现
您认为我应该采取哪种方法?删除属性声明中的= null(duhhh)
或删除超类中的init()并在子类构造函数中显式调用它(这是我想要避免的,因为我必须在100%的时间内编写它。)