java - Overriding a base class method in a derived class -


i have base class a, having method "say" calls constructor of a. heritable classes uses method "say" is. 1 of classes need redefine method. how possible?

for sure, can denote base method "say" abstract, in way, have copy same method "say" in heritable classes.

if redefine method without denoting base 1 abstract, not gonna called.

public abstract class a(){      public a(){         say();  //  <- wanna call method heritable class, if redefined.       }      protected void say(){}; }  public class b extends a(){      public b(){         super();      }      private void say(){}; } 

refactoring 1

public abstract class a(){      public a(){        //  constructor methods                   }      protected void say(){};      protected void executesay(){        say();      } }  public class b extends a(){      public b(){         super();         executesay();      }      @override      protected void say(){}; } 

first of 1 must made clear: calling overridable method constructor well-known antipattern. break code because subclass method invoked before subclass constructor done , observe uninitialized object. should better refrain giving detailed advice on java technicalities involved in achieving antipattern.

the safe way acomplish requirement let construction finish , afterwards call initialize-kind of method. if want ensure initialize invoked, make constructors non-public , provide factory method instead.

unfortunately, java requires quite bit of work on part make work properly.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -