基本上,我要执行的是强制子类调用抽象超类方法(在子类中实现),因此不必在每次创建新的子类时都明确地编写它。
我曾经在超类的构造函数中编写过一次,因为我希望它在每个实现中都强制使用它。
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%的时间编写它。)
您可以通过将声明更改为以下内容来解决此问题:
private TextBox myTextBox;
将null赋值没有任何用处。如果没有超类,它将什么也不做,因为无论如何字段都会初始化为null。由于存在超类,因此它就像脚上的枪声。因此,摆脱它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句