java - Override on Field initialization -


for following example,

public abstract class recorddata {   private mydate mdate  = new mydate(new simpledateformat(""yyyy-mm-dd hh:mm:ss"));    public date getmydate() {     return mdate.getdate();   }       .....   } 

i implementing classes override date format. 1 way of doing have method this:

protected simpledateformat getdateform() {   return new simpledateformat("yyyy-mm-dd hh:mm:ss") } 

so,the initialization should like: mydate mdate = new mydate(getdateform());

is there other convenient way of doing this. potential issues above implementation.

doing bad idea: base class call methog of subclass in constructor, , call method on object hasn't been initialized yet. you'd better pass data needed superclass in constructor:

public abstract class recorddata {     private mydate mdate;      protected recorddata(string datepattern) {         this.mdate = new mydate(new simpledateformat(datepattern));     } } 

doing how others suggest break such basic implementation:

public class subrecorddata extends recorddata {     private simpledateformat dateformat;      public subrecorddata(string pattern) {         this.dateformat = new simpledateformat(pattern);     }      // broken: when method called base class constructor,      // dateformat still null     @override     protected simpledateformat getdateformat() {         return dateformat;     } } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -