Java Reference
In-Depth Information
An object of the ShallowClone class is composed of an object of the DoubleHolder class. The code in the clone()
method of the ShallowClone class is the same as for the clone() method of the DoubleHolder class. The difference
lies in the type of instance variables that are used for the two classes. The DoubleHolder class has an instance variable
of primitive type double , whereas the ShallowClone class has an instance variable of the reference type DoubleHolder .
When the ShallowClone class calls the clone() method of the Object class (using super.clone() ), it receives a
shallow copy of itself. That is, it shares the DoubleHolder object used in its instance variable with its clone.
Listing 7-10 has test cases to test an object of the ShallowClone class and its clone. The output shows that after
you make a clone, changing the value through the original object also changes the value in the cloned object. This is
so because the ShallowClone object stores the value in another object of the DoubleHolder class, which is shared by
both the cloned and the original objects.
Listing 7-10. A Test Class to Demonstrate the Shallow Copy Mechanism
// ShallowCloneTest.java
package com.jdojo.object;
public class ShallowCloneTest {
public static void main(String[] args) {
ShallowClone sc = new ShallowClone(100.00);
ShallowClone scClone = (ShallowClone)sc.clone();
// Print the value in original and clone
System.out.println("Original:" + sc.getValue());
System.out.println("Clone :" + scClone.getValue());
// Change the value in original and it will change the value
// for clone too because we have done shallow cloning
sc.setValue(200.00);
// Print the value in original and clone
System.out.println("Original:" + sc.getValue());
System.out.println("Clone :" + scClone.getValue());
}
}
Original:100.0
Clone :100.0
Original:200.0
Clone :200.0
In a deep cloning, you need to clone all objects referenced by all reference instance variables of an object. You
must perform a shallow cloning before you can perform a deep cloning. The shallow cloning is performed by calling
the clone() method of the Object class. Then you will need to write code to clone all reference instance variables.
Listing 7-11 has code for a DeepClone class, which performs a deep cloning.
 
Search WWH ::




Custom Search