Clone method in Java

Clone method in Java

The process of creating an similar copy of an existing object is called ‘cloning’. In java, clone() method of java.lang.Object class is used for cloning process.

There are two types of cloning or clone method in java –

Shallow Cloning –

Shallow copy of an object is the default version of the clone() method. The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other object as fields, then only references of those objects are copied into clone object, copy of those object are not created. Hence when the clone object is modified, same modification will also affect the original object or vise-versa.

Deep Cloning –

like shallow copy, Deep copy of an object will have exact copy of all the fields of original object. However, in addition, if original object has any references to other objects as fields, then copy of those objects are also created by calling clone() method on them. That means clone object and original object will be 100% disjoint. They will be 100% independent of each other. Any changes made to clone object will not be reflected in original object or vice-versa.

Steps to clone object of the class –

1). The class whose object to be cloned should implement Cloneable interface. This interface belongs to java.lang package. Cloneable interface indicates that the class object are cloneable. If this interface is not implemented, then that class object cannot be cloned and it will give ClassNotSupportException.

2). clone() method of Object class is used for cloning. Object is the super class for every class. So, let us write our own method in the class and call the clone() method.

3). It is also possible to create object, by overriding the clone() method of Object class. Since clone() method is defined as protected Object clone() in Object class.

Shallow Copy Example



Deep Copy Example



Note: ‘Data’ class is common for both examples.


Stay tuned for more updates!

Leave a Reply

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