如何强制对超级方法进行多态调用? [英] How do I force a polymorphic call to the super method?

查看:36
本文介绍了如何强制对超级方法进行多态调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在广泛的层次结构中使用和覆盖的 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
    }
}

这篇关于如何强制对超级方法进行多态调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆