Cloning in Java

Introduction

 
In Java, cloning means creating a duplicate of an object. It is very useful in Java. When we want to make some changes in our object but we do not want to disturb our previous object then we use cloning in Java.
 

Cloning in Java

 
We can define cloning in Java as an aspect of creating a duplicate of the object. We use the clone( ) method in Java to do that. When we want to create a clone of the object of a specific class then we need to implement the interface java.lang.Cloneable in Java. Basically we do cloning in Java when we want to create an identical object to an existing object on which we can do some changes without affecting the original object. This is the sole purpose of cloning in Java. This is required for the creation of the clone in Java. We can also make a new object by the new keyword in Java, but it is a very time-consuming process relative to the cloning in Java. That is why it is very important in Java.
 
Syntax
 
protected Object clone() throws CloneNotSupportedException 
 
Example
  1. package demo;  
  2. public class Demo implements Cloneable {  
  3.  int id;  
  4.  String deptt;  
  5.  Demo(int id, String deptt) {  
  6.   this.id = id;  
  7.   this.deptt = deptt;  
  8.  }  
  9.  protected Object clone() throws CloneNotSupportedException {  
  10.   return super.clone();  
  11.  }  
  12.  public static void main(String args[]) {  
  13.   try {  
  14.    Demo d = new Demo(1091005"C.S.");  
  15.    Demo d1 = (Demo) d.clone();  
  16.    System.out.println(d.id + " " + d.deptt);  
  17.    System.out.println(d1.id + " " + d1.deptt);  
  18.   } catch (CloneNotSupportedException c) {}  
  19.  }  
  20. }  
Output
object cloning
 

Copy Constructor in Java

 
In Java, a copy constructor is also used to copy the object. It captures objects of its own type as a single parameter in Java. In Java, we do not have a default copy constructor. Copy constructors are very easy to implement in Java.
 
Example
  1. package demo;  
  2. public class Demo {  
  3.  private int len;  
  4.  private int bd;  
  5.  private int rad;  
  6.  Demo(int a, int b) {  
  7.   len = a;  
  8.   bd = b;  
  9.  }  
  10.  int area() {  
  11.   return len * bd;  
  12.  }  
  13.  Demo(Demo obj) {  
  14.   len = obj.len;  
  15.   bd = obj.bd;  
  16.  }  
  17.  public static void main(String args[]) {  
  18.   Demo d = new Demo(1015);  
  19.   Demo d1 = new Demo(d);  
  20.   System.out.println("Area of d = " + d.area());  
  21.   System.out.println("Area of d2 = " + d1.area());  
  22.  }  
  23. }  
Output
  
copy constructor
 

Summary

 
This article has explained cloning in Java.


Similar Articles