java—确保在子类构造结束时调用该方法

java—确保在子类构造结束时调用该方法,java,methods,transparent,invocation,Java,Methods,Transparent,Invocation,我有一个抽象类: public abstract class MyComposite extends Composite { protected abstract void initHandlers(); } 以及扩展它的一系列类。如何确保在子类构造结束时调用方法initHandlers()?示例子类: public CollWidget extends MyComposite { public CollWidget() { /** Some stuff t

我有一个抽象类:

public abstract class MyComposite extends Composite {

     protected abstract void initHandlers();
}
以及扩展它的一系列类。如何确保在子类构造结束时调用方法initHandlers()?示例子类:

public CollWidget extends MyComposite {
    public CollWidget() {
        /** Some stuff thats need to be done in this particular case */
        initHandlers(); // This method should be invoked transparently
    }

    @Override
    public void initHandlers() {
        /** Handlers initialisation, using some components initialized in constructor */
    }
}

由于父构造函数总是在子构造函数之前被调用(显式地或隐式地),因此无法自动执行此操作

一种解决办法是:

public abstract class MyComposite {

    public MyComposite() {
        construct();
        initHandlers();
    }

    protected abstract void construct();

    protected abstract void initHandlers();

}

public class CollWidget extends MyComposite {

    @Override
    protected void construct() {
        // called firstly
    }

    @Override
    public void initHandlers() {
        // called secondly
    }

}

没办法让它自动发生,没办法。看看是否可以通过返回设计来避免这种情况,如果确实不能,请清楚地记录这种行为,并让用户在不阅读文档的情况下惨遭失败:)Construct()方法非常好,但在包含这些小部件的presenter中,我必须明确地调用此方法,而默认情况下调用构造函数。我需要通知binder我自己也在构造对象,没有默认的构造函数用法。因此,我为每个小部件增加了一行:)@PiotrSołtysiak好吧,默认情况下也会隐式调用父null构造函数,因此除了
new CollWidget()
之外,不需要添加任何额外的行。看见