Require override of method to call super
Well, I can presume that the initialization in the superclass method is used elsewhere. I would set a flag in the superclass method and check it later when the initialization is needed. More specifically, let's say setupPaint() is superclass method that needs always to be called. so then we can do:
class C {
private boolean paintSetupDone = false;
void setupPaint() {
paintSetupDone = true;
...
}
void paint() { // requires that setupPaint() of C has been called
if (!paintSetupDone) throw RuntimeException("setup not done");
...
}
}
Now if a subclass of C doesn't call the setupPaint() function, there's no way that the (private) flag will be set, and methods requiring the contractual call to the superclass setupPaint(), such as paint() will be able to check and throw that exception.
As noted elsewhere, there is by the way no way of requiring such a contract in java.
solution:
Look at the findBugs project ...
- FindBugs
- Annotations package
Example ...
import javax.annotation.OverridingMethodsMustInvokeSuper;
:
@OverridingMethodsMustInvokeSuper
protected String getLabel(){
...
}
Override:
@Override
protected String getLabel(){
// no call to Super Class!!
// gives a message
...
}
I've been using it for about 3 years. No kittens have been harmed.
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");
}
}
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.