Monday, November 30, 2015

Core Java - How would you defensively copy a Date field in your immutable class?

public final class MyDiary {
    private Date myDate = null;
    public MyDiary(Date aDate){
           this.myDate = new Date(aDate.getTime()); // defensive copying by not exposing the “myDate”                                                                                     reference
     }
     public Date getDate() {
               return new Date(myDate.getTime); // defensive copying by not exposing the “myDate”                                                                                    reference
      }
}

No comments:

Post a Comment