Java Reference
In-Depth Information
// DoubleHolder.java
package com.jdojo.object;
public class DoubleHolder implements Cloneable {
/* The same code goes here as before... */
public DoubleHolder clone() {
Object copy = null;
/* The same code goes here as before... */
return (DoubleHolder)copy;
}
}
With the above declaration for the clone() method, you can write code to clone an object as follows. Note that no
cast is needed anymore.
DoubleHolder dh = new DoubleHolder(100.00);
DoubleHolder dhClone = dh.clone();// Clone dh. No cast is needed
An object may be composed of another object. In such cases, two objects exist in memory separately—a
contained object and a container object. The container object stores the reference of the contained object. When you
clone the container object, the reference of the contained object is cloned. After cloning is performed, there are
two copies of the container object; both of them have references to the same contained object. This is called a shallow
cloning because references are copied, not the objects. The clone() method of the Object class makes only
shallow cloning, unless you code it otherwise. Figure 7-2 shows the memory state of a compound object, where
an object contains a reference of another object. Figure 7-3 shows the memory state when the compound object is
cloned using a shallow cloning. You may notice that in shallow cloning the contained object is shared by the original
compound object and the cloned compound object.
Container
Contained
Figure 7-2. A compound object. The container object stores a reference of another object (Contained object)
Original container object
Container
Contained
Container
Original contained object
Cloned container object
Figure 7-3. Memory state after the container object is cloned using a shallow cloning
 
 
Search WWH ::




Custom Search