Object Cloning in java

Posted By : Sagar Watts | 23-May-2018

Cloning: The process of creating the copy of an object is known as cloning. It creates the exact copy of the object using field-by-field assignment and provides us the new object reference. In Java, it is achieved through the clone() method placed in  java.lang.Object class. To make the object eligible for cloning, you need to implements the required Cloneable interface, a marker interface to provide a marker for the cloning of object.

 

Type of Cloning: There is two type of cloning these are deep cloning and shallow cloning. They are also known as the deep and shallow copy. By default, clone() method creates the shallow copy of the object. To make it enable to do the deep copy, we need to override the clone() method. Here is the description of both the copy processes in Java.

 

Shallow Copy: It is the default type of copy. In this type of copy, the copied object will have all the fields of the original object, except the reference object. That means, if the original object contains the reference of any other object, the copied object will have that reference, any changes made in reference object will also reflect in the copied object. Because of reference, the cloned object is not completely independent from the original object. It is preferred in the case when the object has only primitive fields. Since it does not copy the reference object it is a fast and less expensive process.

 

Deep Copy: Unlike the shallow copy, a deep copy will copy all the fields along with the reference objects. Like the shallow copy, it will copy all the fields of the original object. In addition to that, if the original object contains the reference to any other object, a new copy of that reference object is created using clone() method on the reference object. Which creates a completely independent object. This type of copy is preferred when the object has the reference to other objects as the field value. Because it creates the copy of the every referenced object, it is a slow and expensive process.

 

Thanks,

 

About Author

Author Image
Sagar Watts

Sagar is a bright Web App Lead Developer , he has great knowledge of core Java and advance Java. His hobbies are Net Surfing, Listen Music and Reading Books.

Request for Proposal

Name is required

Comment is required

Sending message..