Java Reference
In-Depth Information
Listing 7-11.
A DeepClone Class That Performs Deep Cloning
// DeepClone.java
package com.jdojo.object;
public class DeepClone implements Cloneable {
private DoubleHolder holder = new DoubleHolder(0.0);
public DeepClone(double value) {
this.holder.setValue(value);
}
public void setValue(double value) {
this.holder.setValue(value);
}
public double getValue() {
return this.holder.getValue();
}
public Object clone() {
DeepClone copy = null;
try {
copy = (DeepClone)super.clone();
// Need to clone the holder reference variable too
copy.holder = (DoubleHolder)this.holder.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return copy;
}
}
If you compare the code in the
clone()
method of the
ShallowClone
and
DeepClone
classes, you will find that for
deep cloning you had to write only one extra line of code.
// Need to clone the holder reference variable too
copy.holder = (DoubleHolder)this.holder.clone();
What will happen if the
DoubleHolder
class is not cleanable? In that case, you would not be able to write the
above statement to clone the
holder
instance variable. You could have cloned the holder instance variable as follows:
// Need to clone the holder reference variable too
copy.holder = new DoubleHolder(this.holder.getValue());
The goal is to clone the
holder
instance variable and it does not have to be done by calling its
clone()
method.
Listing 7-12 shows how your
DeepClone
class works. Compare its output with the output of the
ShallowCloneTest
class to see the difference.