java – 自动调用超类方法

前端之家收集整理的这篇文章主要介绍了java – 自动调用超类方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑下课
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...
        }
    }

我有几个已经开发的B1,B2,… Bn子类.它们都扩展了类A.如果我想在其中添加一个新的功能,最好的方法是定义一个方法在类A内.但是条件是该方法应该在子类的init()方法结束之前自动调用.
一个基本的方法是在子类的init()方法的末尾再次添加atEnd()方法调用.但是有什么其他方法可以聪明地做到吗?

解决方法

一种方法是通过使init()final并将其操作委托给第二个可覆盖的方法
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() {
    // ...
  }
}

每当任何人调用init()时,自动执行序言和结尾语,派生类不必做任何事情.

原文链接:https://www.f2er.com/java/125735.html

猜你在找的Java相关文章