In java, clone is intended to produce a copy of the same object. Means cloning allows to create different
object instance with the same states from existing object instance.
In java clone of an object is created by clone method define inside Object class which is super of all the classes .By convention, the returned object should be obtained by calling
super.clone. If a class and all of its super classes (except
Object obey this convention, it will be the case that
x.clone().getClass() == x.getClass().
By convention, the object returned by this method should be independent
of this object (which is being cloned). To achieve this independence,
it may be necessary to modify one or more fields of the object returned
by super.clone before returning it. Typically, this means
copying any mutable objects that comprise the internal "deep structure"
of the object being cloned and replacing the references to these
objects with references to the copies. If a class contains only
primitive fields or references to immutable objects, then it is usually
the case that no fields in the object returned by super.clone
need to be modified.
The method clone for class Object performs a
specific cloning operation. First, if the class of this object does
not implement the interface Cloneable, then a
CloneNotSupportedException is thrown. Note that all arrays
are considered to implement the interface Cloneable and that
the return type of the clone method of an array type T
is T where T is any reference or primitive type.
Otherwise, this method creates a new instance of the class of this
object and initializes all its fields with exactly the contents of
the corresponding fields of this object, as if by assignment; the
contents of the fields are not themselves cloned. Thus, this method
performs a "shallow copy" of this object, not a "deep copy" operation.
1. Shallow Cloning
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
2. Deep Cloning
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
Important Points about Cloning
1. The object to be cloned must implements Clonable interface
When the Object class finds that the object to be cloned is not an instance of a class that implements Cloneable interface, it throws CloneNotSupportedException.
1. If a class wants to allow clients to clone it's instances, it must override Object's clone method with a public modifier.