java – 自动调用超类方法
发布时间:2020-12-14 16:20:36 所属栏目: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() meth
考虑下课
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()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()时,自动执行序言和结尾语,派生类不必做任何事情. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |