Java Reference
In-Depth Information
Now suppose you plan to change the clone's date, but want to preserve the original
Employee object'sdate.Youcannotdothiswithshallowcloningbecausethechange
isalsovisibletotheoriginal Employee object.Tosolvethisproblem,youmustmodify
thecloningoperationsothatitassignsanew Date referencetothe Employee clone's
hireDate field.Thistask,whichisknownas deep copying or deep cloning ,isdemon-
strated in Listing 2-26 .
Listing 2-26. Deeply cloning an Employee object
class Date
{
int year, month, day;
Date(int year, int month, int day)
{
this.year = year;
this.month = month;
this.day = day;
}
}
class Employee implements Cloneable
{
String name;
int age;
Date hireDate;
Employee(String name, int age, Date hireDate)
{
this.name = name;
this.age = age;
this.hireDate = hireDate;
}
@Override
protected Object clone() throws CloneNotSupportedExcep-
tion
{
Employee emp = (Employee) super.clone();
if (hireDate != null) // no point cloning a null ob-
ject (one that does not exist)
 
Search WWH ::




Custom Search