Use of Object Cloning in Java



The article will explain the use of object cloning in Java and provide an appropriate example to clarify the problem.

What is the Object Cloning in Java?

In Java, object cloning is a way to create an exact copy of an object. We can use the clone() method provided by the Object class to create a clone of an object. When an object is cloned, a new instance of the same class is created, and the fields of the original object are copied to the new object.

The Cloneable interface must be implemented by a class whose object is to be created. If we do not implement the Cloneable interface, the clone() method generates CloneNotSupportedException.

The clone() Method

The clone() method saves an extra processing task for creating an exact copy of an object. If we perform the same task using the new keyword, it will take a lot of processing to perform it. So we can use object cloning.

Syntax

Following is the syntax of the Object clone() method:

protected Object clone() throws CloneNotSupportedException

Example: Cloning using clone() Method

The following example shows the importance of object cloning in Java. We use the clone() method to create a clone (an exact copy) of an object:

public class EmployeeTest implements Cloneable {
   int id;
   String name = "";
   EmployeeTest(int id, String name) {
      this.id = id;
      this.name = name;
   }
   @Override
   public EmployeeTest clone() throws CloneNotSupportedException {
      return (EmployeeTest)super.clone();
   }
   public static void main(String[] args) {
      EmployeeTest emp = new EmployeeTest(115, "Raja");
      System.out.println("Original Object: " + emp.name);
      try {
         EmployeeTest emp1 = emp.clone();
         System.out.println("Clone object: " + emp1.name);
      } catch(CloneNotSupportedException cnse) {
         cnse.printStackTrace();
      }
   }
}

The above program produces the following output:

Original Object: Raja
Clone object: Raja

Example 2: Using a new Keyword

In the example below, we use the new keyword to clone an object. Object cloning is useful when you want to duplicate an object and modify the copy without modifying the original:

public class EmployeeTest {
   int id;
   String name;

   // Constructor
   public EmployeeTest(int id, String name) {
       this.id = id;
       this.name = name;
   }

   //using new keyword to create object clone
   public EmployeeTest copy() {
       return new EmployeeTest(this.id, this.name);
   }

   public static void main(String[] args) {
       EmployeeTest emp = new EmployeeTest(110, "Rahul");
       System.out.println("Original Object: " + emp.name);

       EmployeeTest emp1 = emp.copy();
       System.out.println("Copied Object: " + emp1.name);
   }
}

Following is the output of the above program:

Original Object: Rahul
Copied Object: Rahul
Updated on: 2025-05-27T15:54:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started