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

aho*_*der 13 java polymorphism super

我有一个init方法,通过广泛的层次结构使用和覆盖.然而,每个init调用都扩展了之前的工作.很自然地,我愿意:

@Override public void init() {
   super.init();
}
Run Code Online (Sandbox Code Playgroud)

当然,这将确保一切都被调用和实例化.我想知道的是:我可以创建一种方法来确保调用超级方法吗?如果所有的init都没有调用,那么obejct就会出现故障,所以如果有人忘记调用,我想抛出异常或错误super.

TYFT~Aedon

Liv*_*Liv 12

而不是试图这样做 - 我不认为这是可以实现的顺便说一句! - 一个不同的方法怎么样:

abstract class Base {
 public final void baseFunction() {
   ...
   overridenFunction(); //call the function in your base class
   ...
 }

 public abstract void overridenFunction();
}
...
class Child extends Base {
 public void overridenFunction() {...};
}

...
Base object = new Child();
object.baseFunction(); //this now calls your base class function and the overridenFunction in the child class!
Run Code Online (Sandbox Code Playgroud)

这对你有用吗?

  • 这对于第二代派生类不起作用.如果你定义`class Grandchild extends Child`,那么你不能保证`Grandchild.overridenFunction`会调用`Child.overridenFunction`. (4认同)

Ted*_*opp 8

如果派生类无法调用超类,这是引发异常的一种方法:

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
    }
}
Run Code Online (Sandbox Code Playgroud)