Consider the following class
class A{
public void init(){
//do this first;
}
public void atEnd(){
//do this after init of base cl
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:
abstract class A {
public final void init() {
// insert prologue here
initImpl();
// insert epilogue here
}
protected abstract void initImpl();
}
class B extends A {
protected void initImpl() {
// ...
}
}
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 that init()
calls in the middle:
class A{
public final void init(){
//do this first;
}
protected void initCore() { }
public void atEnd(){
//do this after init of base class ends
}
}
class B1 extends A{
@Override
protected void initCore()
{
//do new stuff.
}
}