Java Cloning

Cloning is the process of creating an exact copy of an existing object.

In projects cloning is common requirement. For example, In e-commerce projects, we may place an order and we may duplicate the order. When we duplicate the order, we need to create clone of an existing order.

Steps to clone an Object

  1. Our class should implement java.lang.Cloneable interface
    • Cloneable is a marker interface
    • JVM throw CloneNotSupportedException if our object is not instanceof Cloneable
  2. Our class should override clone() method of java.lang.Object class
    • To be frank we no need to override a clone() method. But we should define some method which contains cloning logic
      • For example method signature could be public Object createCopy() throws CloneNotSupportedException { }
  3. In our class overridden clone() method, we have to call java.lang.Object.clone() method, which is the actual worker who creates the clone of our object
    • Object.clone() method creates a new instance and copies all fields bit-by-bit of original object to new instance

Let’s try to understand Java cloning with example.  To demonstrate cloning we create two classes Employee and Department with

  1. toString() to show the content of objects
  2. equals() method to compare content of objects
  3. clone() to clone the object
  4. parameterized constructor to populated objects
  5. setters and getters

Example : Java clone

Employee.java

Department.java

JavaCloneDemo.java

Output :

originalEmployee: Employee [id=9999, name=Sekhar, department=Department [id=1234, name=Sales]]
clonedEmployee: Employee [id=9999, name=Sekhar, department=Department [id=1234, name=Sales]]
originalEmployee == clonedEmployee: false
originalEmployee.equals(clonedEmployee): true
——Reference class(Employee.department)——
originalEmployee.department: Department [id=1234, name=Sales]
clonedEmployee.department: Department [id=1234, name=Sales]
originalEmployee.department == clonedEmployee.department: true
originalEmployee.department.equals(clonedEmployee.department): true
—–After Employee.department cloned object modified——
originalEmployee: Employee [id=9999, name=Sekhar, department=Department [id=1234, name=ModifiedDepartmentName]]
clonedEmp loyee: Employee [id=9999, name=ModifiedEmployeeName, department=Department [id=1234, name=ModifiedDepartmentName]]

Great, In the above example, we have added comments to explain each step of the code. Here observations are, all primitive instance variables are copied from original to cloned object successfully. But In the case of reference variables when we modify clonedEmployee.department.name then originalEmployee.department.name also modified(as shown in the above output). This means in the case of reference variables both originalEmployee.department and clonedEmployee.department are pointing to same object. This type of cloning is known as  Shallow Cloning.

Types of Cloning

Cloning in Java can be grouped into two categories based on whether we are copying both primitive and reference variables data.

  1. Shallow Cloning
  2. Deep Cloning

Shallow Cloning

Shallow cloning is “default implementation” in Java. In overridden clone method, if you are cloning only primitives but not all the object types, then this is called shallow cloning. In the above example what ever we implemented is called shallow cloning. The below image is the representation of shallow cloning of our example.

Java Shallow Cloning

Deep Cloning

Deep Cloning means copying everything(both primitives and reference types) from one object to another object. To achieve this, we will need to modify our overridden clone() method of Employee class. Here the rule is all reference type also should implement Cloneable and override clone() method of java.lang.Object class.

In our previous example already both Employee and Department implement Cloneable interface and overridden clone() method of java.lang.Object class. But over previous Employee clone() method supports only shallow cloning. We have to modify Employee.clone() method as follows to support Deep cloning as shown below.

As we modified overridden clone() method in Employee class to support Deep Cloning, Then re-run the test program JavaCloneDemo.java, then we can see the following output.

Deep Copy Output :

originalEmployee: Employee [id=9999, name=Sekhar, department=Department [id=1234, name=Sales]]
clonedEmployee: Employee [id=9999, name=Sekhar, department=Department [id=1234, name=Sales]]
originalEmployee == clonedEmployee: false
originalEmployee.equals(clonedEmployee): true
——Reference class(Employee.department)——
originalEmployee.department: Department [id=1234, name=Sales]
clonedEmployee.department: Department [id=1234, name=Sales]
originalEmployee.department == clonedEmployee.department: false
originalEmployee.department.equals(clonedEmployee.department): true
—–After Employee.department cloned object modified——
originalEmployee: Employee [id=9999, name=Sekhar, department=Department [id=1234, name=Sales]]
clonedEmp loyee: Employee [id=9999, name=ModifiedEmployeeName, department=Department [id=1234, name=ModifiedDepartmentName]]

With this output we can understand that, changing state of the cloned object does not affect the original object. This is called Deep cloning. The below image is the representation of Deep cloning of our example.

Java Deep Cloning

Advantages of Object.clone()

  • Cloning requires much fewer lines of code
  • It is the easiest and most efficient way for copying objects
  • It is the fastest way to copy array

Disadvantages of Object.clone()

  • Object.clone() supports only shallow cloning, To support deep cloning we need to customize our overridden clone method
  • To support cloning we need to make sure all our classes hierarchy need to override clone() method
  • We don’t have any control over object construction because Object.clone() doesn’t invoke any constructor
  • It is not possible to have specific properties exclusions in the cloning

How many ways we can Make a Deep Copy of an Object in Java

There are multiple ways we could use for copying of objects

  • copy constructor
  • factory methods
  • external libraries
  • java cloning

Every approach has their own advantages and disadvantages, based on the business need we have to go for what ever feasible for our requirement.

.

Scroll to Top