Search This Blog

Wednesday, June 06, 2007

What is the main difference between shallow cloning and deep cloning of objects?

The default behaviour of an object’s clone() method automatically yields a shallow copy. So to achieve a deepcopy the classes must be edited or adjusted.

Shallow copy: If a shallow copy is performed on obj-1 as shown in fig-2 then it is copied but its contained objects
are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow
cloning of objects by default when a class implements the java.lang.Cloneable interface.

Deep copy: If a deep copy is performed on obj-1 as shown in fig-3 then not only obj-1 has been copied but the
objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep
cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.

No comments: