Java Reference
In-Depth Information
When the contained objects are copied rather than their references during cloning of a compound object, it is
called deep cloning. You must clone all the objects referenced by all reference variables of an object to get a deep
cloning. A compound object may have multiple levels of chaining of contained objects. For example, the container
object may have a reference of another contained object, which in turn has a reference of another contained object
and so on. Whether you will be able to perform a deep cloning of a compound object depends on many factors. If
you have a reference of a contained object, it may not support cloning and in that case, you have to be content with
shallow cloning. You may have a reference of a contained object, which itself is a compound object. However, the
contained object supports only shallow cloning, and in that case again, you will have to be content with shallow
cloning. Let's look at examples of shallow and deep cloning.
If the reference instance variables of an object store references to immutable objects, you do not need to clone
them. That is, if the contained objects of a compound object are immutable, you do not need to clone the contained
objects. In this case, shallow copy of the immutable contained objects is fine. Recall that immutable objects cannot be
modified after they are created. An immutable object's references can be shared by the multiple objects without any
side effects. This is one of the benefits of having immutable objects. If a compound object contains some references to
mutable objects and some to immutable objects, you must clone the referenced mutable objects to have a deep copy.
Listing 7-9 has code for a ShallowClone class.
Listing 7-9. A ShallowClone Class That Supports Shallow Cloning
// ShallowClone.java
package com.jdojo.object;
public class ShallowClone implements Cloneable {
private DoubleHolder holder = new DoubleHolder(0.0);
public ShallowClone(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() {
ShallowClone copy = null;
try {
copy = (ShallowClone)super.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return copy;
}
}
 
Search WWH ::




Custom Search