fbpx

Courses Offered: Java, Python, Selenium, AWS, Salesforce, DevOps, Angular

What is Cloning In Java? How to use it?

Table of Contents

Cloning

Cloning in Java helps us to create a duplicate of an object. This is achieved by using the clone() method of the Object class.

Following are the steps that need to be followed while cloning an object:-

1. The Cloneable interface from Java. lang package must be implemented by the class whose object is to be cloned. Using the clone() method without implementing the Cloneable interface will generate CloneNotSupportedException.

2. The clone() method needs to be overridden in the class whose object needs to be cloned

Following is the prototype of the clone() method from the Object class.

The clone() method is defined in the Object class.

The syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException  

Advantages of Cloning

  • There’s no requirement to compose lengthy and repetitive code.
  • It stands out as the simplest and most effective method for copying objects, particularly when applied to a pre-existing or older project.
  • The clone() method represents the fastest approach to copying an object’s contents.

Example of Cloning

class Employee implements Cloneable{  

int empid;  

String empname;  

  

Employee(int empid,String empname){  

this.empid=empid; 

this.empname=empname;  

}  
public Object clone()throws CloneNotSupportedException
{  
return super.clone();  
}  

public static void main(String args[])
{  

try{  

Employee e1=new Employee(1,"Amit");
Employee e2=(Employee)e1.clone();  
System.out.println("Nm="+e1.empname);  
System.out.println("Nm="+e2.empname); 

  

}catch(CloneNotSupportedException c){}  

  

}  

}

There are two types of cloning:-

  • Shallow cloning

    • When we duplicate an entity to generate two or more entities, ensuring that modifications in one entity are mirrored in the others, we classify this as a shallow copy.
    • In a shallow copy, additional memory allocation does not occur for the other entities; instead, only the reference is duplicated to those entities.
    • By default, when employing the clone() method, a shallow copy of the object is generated.
    • This implies that a new instance is created, and all the object’s fields are copied to this new instance, resulting in both instances referencing the same memory in the heap.

 

class Data 

{  

 int no=100;

}  

public class ShallowCopyData  

{     

public static void main(String args[])   

{  



Data obj1 = new Data();  

// it will copy the reference, not value  

Data obj2 = obj1;  

obj2.no = 200;   

System.out.println("The value of no is: " + obj1.no);  

}  

}   

In the output, the observed value is 200, reflecting the updated value rather than the original value of 100. This occurs because both obj1 and obj2 point to the same memory location. Hence, any modifications made through the reference variable obj2 will be mirrored in the same way through the reference variable obj1.

Deep cloning

    • When duplicating an entity to generate two or more entities in a manner that ensures alterations in one entity do not impact the others, we refer to this process as a deep copy.
    • Deep copy or cloning involves generating entirely independent duplicate objects in heap memory.
    • This process requires manually assigning values to the second object, ensuring that the values are copied to create an independent replica.
class Data
{  

int no = 100;  
}  
public class DeepCopyData{     
// main method  
public static void main(String argvs[])   
{  
// creating an object of the class ABC  
Data obj1 = new Data();  
  
// it will copy the reference, not value  
Data obj2 = new Data();  
  
obj2.no = 200;  
  
System.out.println("The value of no is: " + obj1.no);  
}  
}  

 In the output, we see the original value of 100, not the updated value of 200. The cause is that obj1 and obj2 reference separate memory locations. Hence, any modifications made through the reference variable obj2 do not reflect when using the reference variable obj1.

Shallow Copy Deep Copy
As no memory is allocated it is fast. As memory is allocated it is slow.
Modifications in one entity are mirrored in the other entity Modifications in one entity are not mirrored in the other entity
The clone() method’s default version facilitates a shallow copy. To enable the clone() method to perform a deep copy, it is necessary to override the clone() method.
The cloned object and the original object are not separate entities. The cloned object and the original object are separate entities.

Our Campus Drive

Subscribe to Us on YouTube

Get daily updates on:
  • Technical
  • Interview 
  • Upcoming Campus 
  • Job-Related Fairs

Are you looking for a better job?
Talk to our Career Expert Now !


Recommended Videos

Request a Callback

For any Queries? Talk to our Experts
+918888809416

Available 24x7 to answer your queries

Enquiry Now

Register Now