Difference between deep cloning and shallow cloning?

Difference between deep cloning and shallow cloning?

Difference between deep cloning and shallow cloning?

Difference between deep cloning and shallow cloning?
  • The process of creating the exact duplicate object is called cloning.
  • The main purpose of cloning is to maintain a backup copy and to preserve the state of an object.
  • We can perform cloning by using clone() of the object class.
  • We can perform cloning only for cloneable objects and object is said to be cloneable if and only if the corresponding class implements cloneable interface.
  • Cloneable interface present in java.lang package and it doesn’t contain any methods it is a marker interface.
  • If we are trying to perform cloning for non-cloneable objects then we will get Runtime exception saying
    CloneNotSupportedException.
  • The clone() method is used to create a copy of an object in Java. In order to use clone() method, class must implement java.lang.Cloneable interface and override protected clone() method from java.lang.Object.A call to clone() method will result in CloneNotSupportedException if that class doesn’t implement Cloneable interface.
  • No constructor is called during cloning of Object in Java.
  • Default implementation of clone() method in Java provides “shallow copy” of the object because it creates the copy of Object by creating the new instance and then copying content by assignment, which means if your class contains a mutable field, then both original object and clone will refer to the same internal object. This can be dangerous because any change made on that mutable field will reflect in both original and copy object. In order to avoid this, override clone() method to provide the deep copy of an object.
  • By convention, clone of an instance should be obtained by calling super.clone() method, this will help to preserve invariant of object created by clone() method i.e. clone != original and clone.getClass() == original.getClass(). Though these are not an absolute requirement as mentioned in Javadoc.
  • A shallow copy of an instance is fine until it only contains primitives and Immutable objects, otherwise, you need to modify one or more mutable fields of the object returned by super.clone(), before returning it to the caller.

Leave a Reply

Your email address will not be published. Required fields are marked *

*