Java – automatically call superclass methods
•
Java
Consider class
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... } }
I have several subclasses of B1, B2,... BN that have been developed They all extend class A. if I want to add a new function, the best way is to define a method in class A But the condition is that the method should be called automatically before the init () method of the subclass ends A basic method is to add the atend () method call again at the end of the init () method of the subclass But is there any other way to do it intelligently?
Solution
One method is to make init() final and delegate its operation to the 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 automatically executed, and the derived class does not have to do anything
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码