需要覆盖方法才能调用super [英] Require override of method to call super
问题描述
我希望当子类重写父类中的方法时,在该子方法中调用 super.method()
。
I want that when a child class overrides a method in a parent class, the super.method()
is called in that child method.
有没有办法在编译时检查这个?
如果没有,当发生这种情况时,如何抛出运行时异常?
Is there any way to check this at compile time?
If not, how would I go about throwing a runtime exception when this happens?
推荐答案
没有办法直接要求这个。但是,你可以做的是:
There's no way to require this directly. What you can do, however, is something like:
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");
}
}
这提供了一个子类可以使用的内部接口点向公共 myExposedInterface()
方法添加自定义行为,同时确保始终执行超类行为,无论子类做什么。
This provides an internal interface-point that subclasses can use to add custom behavior to the public myExposedInterface()
method, while ensuring that the superclass behavior is always executed no matter what the subclass does.
这篇关于需要覆盖方法才能调用super的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!