Use Object.clone()Tag(s): Language


Consider the following example.
import java.util.Date;

class MyData {

 private Date aDate;

 MyData() {
   aDate = new Date();
   }

 public Date getDate() {
   return aDate;
   }
 public void setdate(Date d) {
   aDate = d;
 }
}

public class DemoClone {

  public static void main(String args[]) {

    MyData mydata = new MyData();
    Date d = mydata.getDate();
    System.out.println(d);
    d.setTime(1000);
    System.out.println(d);
    System.out.println(mydata.getDate());
    // Sat Apr 19 23:17:43 EDT 2003
    // Wed Dec 31 19:00:01 EST 1969
    // Wed Dec 31 19:00:01 EST 1969   which is no good
  }
}
Even if aDate is declared as private, it is possible to modify because a Date object is mutable and we have a reference to it. The solution is to return a copy of aDate, so even if you have reference to it, any modification will be done on the copy, not the original.
import java.util.Date;

class MyData {

 private Date aDate;

 MyData() {
   aDate = new Date();
   }

 public Date getDate() {
   return (Date)aDate.clone();
   }
 public void setdate(Date d) {
   aDate = d;
 }
}

public class DemoClone {

  public static void main(String args[]) {

    MyData mydata = new MyData();
    Date d = mydata.getDate();
    System.out.println(d);
    d.setTime(1000);
    System.out.println(d);
    System.out.println(mydata.getDate());
    // Sat Apr 19 23:17:43 EDT 2003
    // Wed Dec 31 19:00:01 EST 1969
    // Sat Apr 19 23:17:43 EDT 2003   which is good
  }
}

blog comments powered by Disqus