如何强制对超级方法进行多态调用?

2022-01-24 00:00:00 super polymorphism java

我有一个在广泛的层次结构中使用和覆盖的 init 方法.然而,每个 init 调用都扩展了前一个所做的工作.所以很自然,我会:

I have an init method that is used and overridden through out an extensive heirarchy. Each init call however extends on the work that the previous did. So naturally, I would:

@Override public void init() {
   super.init();
}

这自然会确保所有内容都被调用和实例化.我想知道的是:我可以创建一种方法来确保调用超级方法吗?如果没有调用所有的 init,则对象中存在故障,因此如果有人忘记调用 super,我想抛出异常或错误.

And naturally this would ensure that everything is called and instantiated. What I'm wondering is: Can I create a way to ensure that the super method was called? If all of the init's are not call, there is a break down in the obejct, so I want to throw an exception or an error if somebody forgets to call super.

TYFT~艾顿

推荐答案

如果派生类未能调用超类,以下是引发异常的一种方法:

Here's one way to raise an exception if a derived class fails to call up to the superclass:

public class Base {
    private boolean called;
    public Base() { // doesn't have to be the c'tor; works elsewhere as well
        called = false;
        init();
        if (!called) {
            // throw an exception
        }
    }
    protected void init() {
        called = true;
        // other stuff
    }
}

相关文章