Friday, June 13, 2008

Difference between Shallow Copy and Deep Copy

Shallow Copy

This is a result of the default cloning functionality provided by the Object.clone() method if the class has non-primitive data type members as well. Shallow Copy concept is not applicable to the classes having only primitive data type members as in that case the default cloning will also result into a Deep Copy only.

In case of Shallow Copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves. That's why the name Shallow Copy. Read more about Cloning and see the memory diagram to understand it better - Cloning in Java >>

Deep Copy

We need to override the clone() method for the classes having non-primitive type members to achieve Deep Copy as Deep Copy requires the member objects to be cloned as well, which is not done by the default cloning mechanism. Why is it not done by the default cloning? Because clone() is a method of the Object class and at that level it's not known what a typical class can have as its members and hence only a field-by-field copy approach has been provided as the default cloning mechanism.

Implementing Deep Copy in Java

For Deep Copy, we need to ensure that the member classes also implement the Cloneable interface otherwise calling the clone() method on the objects of those classes will result into CloneNotSupportedException. So, to implement Deep Copy, we first need to ensure that all the member classes (at all the levels - like if the member class itself has a member of some class type then that class as well... and so on) are implementing the Cloneable interface. After that we override the clone() method in all those classes (even in the classes where we have only primitive type members otherwise we would not be able to call the protected clone()method of Object class on the instances of those classes inside some other class ... a typical restriction of the protected access. We'll cover this in a separate article) and finally calling clone() method on the object members in the overriden clone() method definition. See the Java source Code (for a sample implementation by overriding clone() method) here - Deep Copy Implementation in Java >>

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.


No comments: