The clone() method of Object performs a shallow copy of an object. This means that primitive fields are copied, but objects within the cloned object are not copied. Rather, the references within the new object point to the objects referenced by the original object. This can sometimes lead to unexpected results. Sometimes a deep copy of an object is needed. In a deep copy, rather than references in the new object pointing to the same objects as the original class, the references point to new objects (whose values have been copied over).

A typical way of implementing a deep clone is to go through a class and write code to create new objects and copy over all of the values to these new objects. This can be a time-consuming process if the object being cloned is complicated. A simple way of performing a deep clone is for all of the classes that make up a class to implement the Serializable interface. If this is the case, we can serialize all of the values of the object and then deserialize all of these values to a new object. This in essence is a shortcut to performing a deep copy, since all of the values get copied over into new objects.

The CloneExample class shows an example of this technique. We can see a standard clone() method that performs a shallow copy. We can also see a deepClone() method that utilizes the Serializable trick to perform the deep copy. The CloneExample class contains two fields, an int and a Thing. These fields are used to demonstrate the differences between a shallow copy (that copies over primitive types but not objects) and a deep copy (that copies over primitive types and objects).

Before cloning
ce:num:3, thing:Fred
After cloning, setting ce num to 5
After cloning, setting ce thing name to Barney
ce:num:5, thing:Barney
ceShallowClone:num:3, thing:Barney
cdDeepClone:num:3, thing:Fred
Notice that changing ce thing name to Barney changed ceShallowClone's thing name to Barney.
This is because the copy was shallow, and ce's thing and ceShallowClone's thing point to the same Thing.
Notice that ceDeepClone's thing name is Fred. This is because the deep copy resulted in ceDeepClone having its own Thing.

Using this technique, the classes that make up the class being cloned need to be Serializable. If they don't, this technique doesn't work.