Cloning in Java
Cloning is done for copying the object, cloning can be done using shallow or deep copy
Few key points about clone method
1) Definition of clone method -
protected native Object clone() throws CloneNotSupportedException;
Clone is a protected method - clone method can’t be called outside class without inheritance.
Clone is native method, if not overridden its implementation is provided by JVM.
It returns Object - Means explicitly cast is needed to convert it to original object.
2) By default clone method do shallow copy.
3) Class must implement marker interface java.lang.Cloneable. If class doesn’t implement Cloneable than calling clone method on its object will throw CloneNotSupportedException.
4) shallow copy- If we implement Cloneable interface, we must override clone method and call super.clone() from it, invoking super.clone() will do shallow copy.
5) Deep copy - We need to provide custom implementation of clone method for deep copying. When the copied object contains some other object its references are copied recursively in deep copy.