需要覆盖方法才能调用super

And*_*par 29 java super

我希望当子类重写父类中的方法时,super.method()会在该子方法中调用它.

有没有办法在编译时检查这个?
如果没有,当发生这种情况时,我将如何抛出运行时异常?

aro*_*oth 40

没有办法直接要求这个.但是,你可以做的是:

public class MySuperclass {
    public final void myExposedInterface() {
        //do the things you always want to have happen here

        overridableInterface();
    }

    protected void overridableInterface() {
        //superclass implemention does nothing
    }
}

public class MySubclass extends MySuperclass {
    @Override
    protected void overridableInterface() {
        System.out.println("Subclass-specific code goes here");
    }
}
Run Code Online (Sandbox Code Playgroud)

这提供了一个内部接口点,子类可以使用它向公共myExposedInterface()方法添加自定义行为,同时确保始终执行超类行为,无论子类做什么.

  • +1 ..甚至更好,在基类中将overridableInterface()标记为抽象. (7认同)

wil*_*ill 11

解:

看看findBugs项目......

示例......

    import javax.annotation.OverridingMethodsMustInvokeSuper;
       :

    @OverridingMethodsMustInvokeSuper
    protected String getLabel(){
       ... 
    }
Run Code Online (Sandbox Code Playgroud)

覆盖:

    @Override
    protected String getLabel(){
       // no call to Super Class!!
       // gives a message 
       ... 
    }
Run Code Online (Sandbox Code Playgroud)

我已经使用它大约3年了.没有小猫受到伤害.