自动调用超类方法 [英] Call super class method automatically

查看:68
本文介绍了自动调用超类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下课程

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()方法调用.但是还有其他方法可以巧妙地做到这一点吗?

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

推荐答案

做到这一点的一种方法是使init()为final,并将其操作委派给第二个可重写的方法:

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() {
    // ...
  }
}

每当有人调用init()时,序言和结语都会自动执行,并且派生类不必执行任何操作.

Whenever anyone calls init(), the prologue and epilogue are executed automatically, and the derived classes don't have to do a thing.

这篇关于自动调用超类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆