V_M
V_M

Reputation: 203

Call super class method automatically

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 ??

Upvotes: 10

Views: 5273

Answers (4)

Michael
Michael

Reputation: 44200

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().

Upvotes: 0

NPE
NPE

Reputation: 500673

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.

Upvotes: 22

duffymo
duffymo

Reputation: 308938

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

Upvotes: 4

SLaks
SLaks

Reputation: 887777

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

Upvotes: 3

Related Questions