基本上,我想要做的是强制子类调用抽象超类方法(在子类中实现),因此每次创建新子类时我都不必显式地编写它.
我在超类的构造函数中写了一次,因为我希望它强制它用于每个实现.
- 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类,所以它不能实例化,它必须将任务委托给它的子类,所以为什么它们不能调用抽象但现在实施方法?