Call super class method automatically

前端 未结 4 1125
北海茫月
北海茫月 2021-01-17 17:27

Consider the following class

class A{
    public void init(){
        //do this first;
    }
    public void atEnd(){
        //do this after init of base cl         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-17 18:03

    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.

提交回复
热议问题