Life of MAK
Life of MAK

Reputation: 1434

Override on Field initialization

For the 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 would like implementing classes to override the date format. One way of doing this is to have a method like this:

protected SimpleDateFormat getDateForm() {
  return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
}

So,the initialization should be like: MyDate mDate = new MyDate(getDateForm());

Is there any other convenient way of doing this. What are the potential issues with the above implementation.

Upvotes: 0

Views: 624

Answers (1)

JB Nizet
JB Nizet

Reputation: 691943

Doing that is a very bad idea: your base class would call a methog of the subclass in its constructor, and would thus call a method on an object that hasn't been initialized yet. You'd better pass all the data needed by the superclass in its constructor:

public abstract class RecordData {
    private MyDate mDate;

    protected RecordData(String datePattern) {
        this.mDate = new MyDate(new SimpleDateFormat(datePattern));
    }
}

Doing how others suggest would completely break with such a basic implementation:

public class SubRecordData extends RecordData {
    private SimpleDateFormat dateFormat;

    public SubRecordData(String pattern) {
        this.dateFormat = new SimpleDateFormat(pattern);
    }

    // broken: when this method is called by the base class constructor, 
    // dateFormat is still null
    @Override
    protected SimpleDateFormat getDateFormat() {
        return dateFormat;
    }
}

Upvotes: 6

Related Questions