«Back to Home

Core Java

Topics

Object Cloning In Java

Object Cloning

In Java, the object cloning is used to create an exact copy of an object. Object class have a clone() method, which is used to clone an object.
 
Advantage of Object cloning

Object cloning is mainly used to less processing task in Java.
 
The clone() method is created in the object class.
 
Syntax of clone method

19

The java.lang.Cloneable interface should be implemented by the class, whose object clone, we want to create. If we don't implement Cloneable interface, clone() method produces an error (CloneNotSupportedException).
 
Let’s see an example of object cloning, given below.
 
Code
  1. public class Car implements Cloneable {  
  2.     int carno;  
  3.     String carname;  
  4.     Car(int carno, String carname) {  
  5.         this.carno = carno;  
  6.         this.carname = carname;  
  7.     }  
  8.     public Object clone() throws CloneNotSupportedException {  
  9.         return super.clone();  
  10.     }  
  11.     public static void main(String args[]) {  
  12.         try {  
  13.             Car c1 = new Car(2364588"Swift Dezire");  
  14.             Car c2 = (Car) c1.clone();  
  15.             System.out.println(c1.carno + " " + c1.carname);  
  16.             System.out.println(c2.carno + " " + c2.carname);  
  17.         } catch (CloneNotSupportedException e) {}  
  18.     }  
  19. }  
17

Output

18

In the example, mentioned above, we have two reference variables that have the same value. Thus, the clone() copies the exact values of an object to another. Therefore, we don’t need to write the explicit code to copy the value of an object to another.
 
If we create another object by new keyword and assign the values of another object with this one, it will require a lot of processing on this object. Thus, to save the extra processing task, we use clone() method.
 
Usage of clone method
  • Saves the extra processing task.

  • Create the exact copy of an object.
Summary

Thus, we learnt that object cloning is used to create an exact copy of an object and also learnt its advantages in Java.