1

我有抽象类:

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 */
    }
}
4

1 回答 1

1

There is no way to do it automatically, since the parent constructor is always called before the child one (explicitely or implicitely).

One solution workaround could be:

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
    }

}
于 2014-07-29T09:51:06.320 回答