Consider the following class
class A{
public void init(){
//do this first;
}
public void atEnd(){
//do this after init of base class ends
}
}
class B1 extends A{
@Override
public void init()
{
super.init();
//do new stuff.
//I do not want to call atEnd() method here...
}
}
I have several B1, B2,... Bn child classes which are already developed. All of them extend class A. If I want to add a new functionality in all of them, the best place to do so is define that in a method within class A. But the condition is that the method should always get called automatically just before the init() method of child class ends. One basic way to do so is to again add atEnd() method call at end of init() method of child classes. But is there any other way to do this smartly ??
Another thought would be to weave in an aspect. Add before and after advice to a pointcut.
The other answers are reasonable workarounds but to address the exact question: no, there is no way to do this automatically. You must explicitly call
super.method()
.One way to do this is by making
init()
final and delegating its operation to a second, overridable, method:Whenever anyone calls
init()
, the prologue and epilogue are executed automatically, and the derived classes don't have to do a thing.Make
init()
final
, and provide a separate method for people to override thatinit()
calls in the middle: