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

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

问题描述

我有一个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();
}

当然,这将确保调用和实例化所有内容。我想知道的是:我可以创建一种方法来确保调用super方法吗?如果所有的init都没有调用,那么obejct就会出现故障,所以如果有人忘记调用 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~Aedon

TYFT ~Aedon

推荐答案

以下是提出异常的一种方法派生类无法调用超类:

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
    }
}

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

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