Java Reference
In-Depth Information
emp.hireDate
=
new
Date(hireDate.year,
hireDate.month, hireDate.day);
return emp;
}
public
static
void
main(String[]
args)
throws
CloneNotSupportedException
{
Employee e1 = new Employee("John Doe", 46, new
Date(2000, 1, 20));
Employee e2 = (Employee) e1.clone();
System.out.println(e1 == e2); // Output: false
System.out.println(e1.name == e2.name); // Output:
true
System.out.println(e1.hireDate == e2.hireDate); //
Output: false
System.out.println(e2.hireDate.year+"
"+e2.hireDate.month+" "+
e2.hireDate.day); // Output: 2000
1 20
}
}
Listing2-26 declares Date and Employee classes.The Date classdeclares year ,
month , and day fields and a constructor.
Employee overrides the clone() method to deeply clone the hireDate field.
Thismethodfirstcalls Object 's clone() methodtoshallowlyclonethecurrent Em-
ployee object'sinstance fields, andthen stores the new object'sreference in emp .It
next assigns a new Date object's reference to emp 's hireDate field; this object's
fields are initialized to the same values as those in the original Employee object's
hireDate instance.
At this point, you have an Employee clone with shallowly cloned name and age
fields,andadeeplycloned hireDate field.The clone() methodfinishesbyreturn-
ing this Employee clone.
Note If you are not calling Object 's clone() method from an overriding
clone() method (because you prefer to deeply clone reference fields and do your
Search WWH ::




Custom Search