Object Cloning in Java

Cloning is the process of creating a copy of an object. Java’s Object class contains a clone() method which can be overridden by any class that needs to support cloning. Object cloning is different from assigning an object to a new variable where the same memory location is assigned to the new variable, cloning creates a new memory location and copies the content of the object being cloned to the new location.

Signature of clone() method:

protected Object clone() throws CloneNotSupportedException

Notice that the clone() method throws CloneNotSupportedException. Any class that needs to support cloning must implement the Cloneable interface to avoid this exception. Cloneable is a marker interface which indicates the JVM that the object of the class supports cloning.

Note: Object class itself doesn't implement Cloneable. Thus if any object of type Object is tried to be cloned, it would throw CloneNotSupportedException.


Why Cloneable doesn’t implement clone()

Since every class that supports cloning needs to implement Cloneable interface, why doesn’t it itself declare a clone() method which the implementing class can override?

The Object.clone() method contains the actual native-level code that makes a copy of the Java object.

// clone() method from Object class
protected native Object clone() throws CloneNotSupportedException;

The method is made protected, since subclasses might want to restrict the access to it. If Cloneable interface declares a clone() method, it has to make it public (Since interface should always have public methods). Thus every class that implements Cloneable should override it, thus making the method publicly accessible.


Sample Code

The sample code below demonstrates object cloning in Java. We have written an employee class that we will clone. To support cloning our Employee class should implement Cloneable and override the clone() method.

public class Employee implements Cloneable{
    
    private String name;
    
    private int salary;
    
    public Employee(String name, int salary){
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public int getSalary() {
        return salary;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class EmployeeMain {
	
    public static void main(String[] args) {
	try{
	    Employee emp = new Employee("Ashutosh", 50000);
	    Employee empClone = (Employee) emp.clone();
			
	    System.out.println("EMP --> name: " + emp.getName() + ", salary: "+ emp.getSalary());
	    System.out.println("EMP CLONE --> name: " + empClone.getName() + ", salary: "+ empClone.getSalary());
			
	}catch(CloneNotSupportedException ce){
	    ce.printStackTrace();
	}
    }
}

Executing the main class above would print the following output on console:

EMP --> name: Ashutosh, salary: 50000
EMP CLONE --> name: Ashutosh, salary: 50000

Note: The constructor of the class is never called when an object is cloned. If any initialization code written in the constructor it will not be called for the cloned object. It is our responsibility to initialize the cloned object properly.


Copy Constructor

A copy constructor is a constructor which takes its own type as its only parameter. It is essentially used to create a copy of the object. Shown below is a copy constructor for the Employee class we used earlier in our example:

public Employee(Employee emp){
    this.name = emp.name;
    this.salary = emp.salary;
}
RELATED ARTICLES

2 ways to Create a Thread in Java

Threads in Java can be created in 2 different ways, extending the Thread class and implementing the Runnable interface. This article explains the two ways with suitable examples.

View Article

4 Different Ways of Creating an Object in Java

Most of us have created object using new operator in Java. Did you know the other ways to create objects in Java. This article talks about 4 different ways of creating objects in Java.

View Article

Using AutoCloseable with 'try-with-resources'

Java 7 added the java.lang.AutoCloseable interface that developers can implement in their custom classes for using them with try-with-resources.

View Article

Chained Exception

Chained exception is a feature introduced with JDK 1.4, which allow developers to associate an exception with another exception.

View Article

Shallow Cloning and Deep Cloning

Cloning an object can happen in two ways Deep and Shallow Cloning. In shallow cloning only object references are copied while in deep copy actual objects are copied to the newly cloned object.

View Article

Exception Handling in Inheritance

There are certain rules that must be followed while throwing exceptions in inheritance and overriding methods. This article discuss about these rules.

View Article

Garbage Collection in Java

Java Garbage Collector is a boon to Java developers; it allows developers to program without worrying about memory management. This article describes the working of Java Garbage Collector in details.

View Article

Understanding static and final in Java

Java provides various modifiers which when used with variables, methods or classes, provides them with special properties. Static and final are are two such modifiers which are used frequently by Ja..

View Article

Try-with-resources Statement in Java 7

Java 7 introduces the new 'try-with-resources' statement which help developers to overcome the tedious task of closing the resources that have been used in the program.

View Article

Varargs: Variable Arguments to Methods

Java 5 introduced a new feature called varargs, which allows methods to accept variable number of arguments. They are useful in cases where the number of arguments to be passed to a method is unknown.

View Article