Interview Questions

What is difference between deep and shallow cloning?

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

What is difference between deep and shallow cloning?

The differences are as follows:
* Consider the class:
public class MyData{
String id;
Map myData;
}

The shallow copying of this object will have new id object and values as “” but will point to the myData of the original object. So a change in myData by either original or cloned object will be reflected in other also. But in deep copying there will be new id object and also new myData object and independent of original object but with same values.

* Shallow copying is default cloning in Java which can be achieved using clone() method of Object class. For deep copying some extra logic need to be provided.

(Continued on next question...)

Other Interview Questions