Call super class method automatically

前端 未结 4 1121
北海茫月
北海茫月 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 17:56

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

    0 讨论(0)
  • 2021-01-17 17:57

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-17 18:04

    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.
        }
    }
    
    0 讨论(0)
提交回复
热议问题