Cloneable Interface – Shallow Copy and Deep Copy with Examples

Cloneable Interface – Shallow Copy and Deep Copy with Examples:
Cloneable means making an exact copy of original object.

Inorder to invoke objects clone method, it should have implemented Cloneable interface. If we try to invoke an object that haven’t implemented Cloneable interface will result in exception “CloneNotSupported”.

  • When a clone is made and if the class has only primitive types, then it will be cloned in new object and will give new references.
  • If there are any member variables present in the class, still object will be cloned but the member variables present in original object and cloned object will point to the same reference.

By default, object’s clone method uses Shallow Copy.

What is Shallow Copy?
It will have the exact copy of the object, if any fields of the object is an reference to another object only the reference address of the object is copied. (Only memory addresses are copied).i.e. If any change made in the field of an object will reflect in the cloned object too.

What is Deep Copy?
If any fields of the object is an reference of another field, It will have the new copy of referred object and not the referred address. So any change made in the original object will not reflect in cloned object.

 

Now let us see an example for Cloneable with ShadowCopy

Department.java

Student.java

We have implemented Cloneable interface and have overridden Clone() method.


From the output, we can see whenever a change is made in Department object and even though it is updated only in original object the change gets reflected in Cloned object too. This is Shallow Copy.

DeepCopy

We are overriding the Clone method for the deep copy to work. We are setting the variables separately so it does not impact the cloned object.

From the output, we can see when a change for Department object is made in original object it does not reflect in the cloned object.

 

Read More