Call super class method automatically

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.
    }
}

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.


Another thought would be to weave in an aspect. Add before and after advice to a pointcut.