Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
edited tags
Link
JasonMArcher
  • 15.1k
  • 22
  • 59
  • 53
Source Link

Java deep clone issue

I am learning Java about object clone. I am really confused by shallow clone and deep clone. Below is a sample code from Core Java

public class Employee implements Cloneable { private String name; private Date hireDay; public Employee(String n,double s) { this.name=n; hireDay=new Date(); } public void setHireDay(int year,int month,int day) { Date newhireDay=new GregorianCalendar(year,month-1,day).getTime(); hireDay.setTime(newhireDay.getTime()); } public Employee clone() throws CloneNotSupportedException { Employee cloned=(Employee) super.clone(); //clone mutable fields //cloned.hireDay=(Date) hireDay.clone(); return cloned; } public String toString() { return "Employee[name=]"+ name+" salary= "+salary+" hireday.getTIme() "+hireDay+"]"; } } public class cloneTest { public static void main(String[] args) { try{ Employee original =new Employee("john"); Employee cloned=original.clone(); original.setHireDay(1993,2,22); cloned.setHireDay(2000,11,22); System.out.println("original="+original); System.out.println("cloned= "+cloned); } catch(CloneNotSupportedException e){ e.printStackTrace(); } } } 

In this case, output of original object and cloned object are the same.Since I didn't clone the mutable field,the change made on cloned objects will affects original object. But when I change the method setHireDay into this:

public void setHireDay(int year,int month,int day) { hireDay=new GregorianCalendar(year,month-1,day).getTime(); } 

I did change the value of field hireDay in cloned object but it doesn't affect original object.I don't know why