Object Cloning in Java | Clone() Method, Example

The process of making an exact copy of an existing object is called object cloning in Java.

Cloning an object means an exact copying the content of an object bit by bit.

The object cloning is a way to make an exact copy of an object bit wise. In cloning, the original object and cloned object will be exactly the same bit by bit.

If the original object contains some data into it, it also automatically comes into the cloned object.

Why do we need Object cloning in Java?


Java language does not provide an automatic mechanism to clone (make a copy) an object. We know that when we assign a reference variable to another reference variable, only the reference of the object is copied, not the content of the object.

This means that the original and copy references points to the same object. If we make a change to either variable, also affects another. Look at the below figure with the code snippet to understand better.

Java object cloning example

Employee original = new Employee("Bob", 60000.0);
Employee copy = original;
copy.raiseSalary(10); // It will also change the original.

If you would like to make a copy to be a new object, use clone() method of Object class. A sample of code is something like this:

Employee copy = (Employee)original.clone();
copy.raiseSalary(10); // ok. original unchanged.

Let’s understand the clone() method of Object class in more detail.

clone() Method in Java


To clone objects of a class, use clone() method of Object class in the class. Object class provides a clone() method that creates a bitwise duplicate copy of the object on which we invoke it.

The general declaration of clone() method in the Object class is as follows:

protected Object clone() throws CloneNotSupportedException

We need to observe the following things about the declaration of clone() method:

1. Since clone() method has declared as protected, therefore, we cannot call it from the client code. The following code is not valid:

Object obj = new Object();
Object clone = obj.clone(); // Error. cannot access protected clone() method.

If we declare clone() method public in the class, we can use the above client code to clone objects of a class.

2. The return type of clone() method is class Object. It means that we will need to cast the returned value of clone() method when we will call the clone method. For example, suppose MyClass is cloneable. The cloning code will look like this:

MyClass mc = new MyClass();
MyClass clone = (MyClass)mc.clone(); // type casting.

3. The clone() method of Object class throws an exception named CloneNotSupportedException. It means when we call clone() method, then we must place the call in a try-catch block, or rethrow the exception.

Steps to clone object of a class


There are the following steps that must take to clone the object of a class:

1. Implement the empty cloneable interface. Only a class that implements Cloneable interface can be cloned.

Cloneable interface is a marker interface declared in java.lang package. This interface has no members. It shows that class objects are cloneable.

If we do not implement Cloneable interface, clone() method produces an exception named CloneNotSupportedException and class objects will not clone.

2. Write your own method with a public access modifier in the class and call the clone() method of Object class using super keyword. The snippet code is something like this:

public Object myClone() // user defined method
{
   return super.clone(); // create a cloned object and return it.
}

3. It is also possible to create a cloned object by overriding clone() method of Object class with a public access modifier. The overriding code is something like this:

protected Object clone() // this method overrides Object's clone() method.
{
   return super.clone();
}

Why use clone() method?


The clone() method saves the extra processing task for cloning an object of a class. If we do it using a new keyword, then it will take a lot of processing time to be performed on the object. That’s why we use clone() method for object cloning.

Types of Object cloning in Java


There are two types of object cloning in Java. They are as follows:

  • Shallop cloning
  • Deep cloning

Let’s understand in the brief.

Shallow cloning: When we modify the cloned object, and the same modification also affects in the original object, then this type of cloning is called shallow cloning.

Deep cloning: When we modify the cloned object, and the same modification does not affect the original object, then this type of cloning is called deep cloning.

Object Cloning Example Programs


Let’s create a Java program to clone Employee class object with name and id details. The Employee class will implement Cloneable interface.

In the Employee class, we will define a user defined method myClone(), that calls super class (Object class) clone() method to clone Employee class object.

Program code 1:

// Object cloning example.
package javaProgram;
public class Employee implements Cloneable {
// Instance variables declaration.
   String name;
   int id;
// Create a constructor to initialize the instance variables.
   Employee(String name, int id) {
	this.name = name;
	this.id = id;
   }
// Create an instance method to display the employee details.
   void getData() {
	System.out.println("Employee's name: " +name);
        System.out.println("Employee's id: " +id);
   }
// Create a user defined method for Cloning the present class object.
   public Object myClone() throws CloneNotSupportedException {
	return super.clone();
   }
}
package javaProgram;
public class CloningTest {
public static void main(String[] args) throws CloneNotSupportedException 
{
// Create an object of Employee class using new operator.
   Employee emp1 = new Employee("John", 10);
   System.out.println("Data of original object: ");
   emp1.getData();
 
// Create another object by cloning emp1. 
// Since clone() method returns object of Object class type, it must be converted into Employee type. 
   Employee emp2 = (Employee)emp1.myClone();
   System.out.println("Data of cloned object: " );
   emp2.getData();
  }
}
Output:
      Data of original object: 
      Employee's name: John
      Employee's id: 10
      Data of cloned object: 
      Employee's name: John
      Employee's id: 10

As you can observe in this example, both reference variables have the same value. Thus, Object’s clone() method copies the values of an object to another.


We can also rewrite the above program by overriding the clone() method of Object class. Replace the myClone() method code with the below code:

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

Let us take one more example program based on object cloning.

Program code 2:

// Another Object cloning example.
package javaProgram;
public class Employee implements Cloneable {
   String name;
// Create a constructor to initialize the instance variable.
   Employee(String name) {
	this.name = name;
   }
public void setData(String name) {
   this.name = name;
}
 public String getData() {
   return this.name;
 }
 public Object clone() {
  Employee emp =  null;
  try {
 // Calling clone() method of Object class, which will copy bitwise and return the reference of the clone.
    emp = (Employee)super.clone();  
  }
  catch(CloneNotSupportedException e) {
  // If anything goes incorrect during cloning, display error details.
     e.printStackTrace();
  }
  return emp;
 }
}
package javaProgram;
public class CloningTest {
public static void main(String[] args) throws CloneNotSupportedException 
{
// Create an object of Employee class using new operator.
   Employee emp = new Employee("John");
// Clone emp.
   Employee empClone = (Employee)emp.clone();
 
// Print employee name in original and clone.
   System.out.println("Original employee name: " +emp.getData());
   System.out.println("Clone employee name: " +empClone.getData());
   
// Change the employee name in original and clone.
   emp.setData("Bob");
   empClone.setData("Herry");
   
// Print employee name in original and clone again.
   System.out.println("Original employee name: " +emp.getData());
   System.out.println("Clone employee name: " +empClone.getData());   
  }
}
Output:
       Original employee name: John
       Clone employee name: John
       Original employee name: Bob
       Clone employee name: Herry

Advantage of Object cloning in Java


Object’s clone() method is a popular and easy way to copy class objects. There are the following advantages of using clone() method. They are:

1. We do not need to write lengthy and repetitive codes. Just create an abstract class with 4 to 5 lines of long clone() method.

2. The clone() method provides an easy and efficient way of making duplicate copies of class objects. Especially when we are applying it to an already developed or an old project.

3. This method provides a fastest way to copy an array.

Disadvantage of Object cloning


A list of some disadvantages of using clone() method is as follows:

1. To use Object’s clone() method, we will have to implement a Cloneable interface, defining the clone() method, and handling CloneNotSupportedException, and finally, have to calling Object.clone() method, etc.

2. Object’s clone() method is protected, so we need to define our own clone() method and indirectly call Object.clone() from it.

3. It supports only shallow copying. If we want deep cloning, then need to override the clone() method of Object class.

4. If we define clone() method in the subclass, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Else, super.clone() chain will fail.

5. The clone() method of Object class doesn’t call any constructor, so we don’t have any control over object construction.


In this tutorial, you learned object cloning in Java with an example program. Hope that you will have understood the basic concept of clone() method of Object class and its using advantages and disadvantages.
Thanks for reading!!!