Call super class method automatically

2020-04-02 08:03发布

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

4条回答
Viruses.
2楼-- · 2020-04-02 08:29

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

查看更多
forever°为你锁心
3楼-- · 2020-04-02 08:40

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

查看更多
Ridiculous、
4楼-- · 2020-04-02 08:42

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.

查看更多
做个烂人
5楼-- · 2020-04-02 08:45

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.
    }
}
查看更多
登录 后发表回答