Cloning is the process of creating a copy of an Object. Java Object class comes with native clone() method that returns the copy of the existing instance.

Since Object is the base class in Java, all objects by default support cloning.

Java Object Cloning

java-clone-object-cloning-in-java

If you want to use Java Object clone() method, you have to implement the java.lang.Cloneable marker interface. Otherwise, it will throw CloneNotSupportedException at runtime.

Also Object clone is a protected method, so you will have to override it.

Let’s look at Object cloning in Java with an example program.

We are using Object clone() method, so we have implemented the Cloneable interface. We are calling the superclass clone() method i.e. Object clone() method.

Using Object clone() Method

Let’s create a test program to use the object clone() method to create a copy of the instance.

Output:

CloneNotSupportedException at Runtime

If our Employee class won’t implement Cloneable interface, the above program will throw CloneNotSupportedException runtime exception.

Understanding Object Cloning

Let’s look into the above output and understand what’s happening with Object clone() method.

  1. emp and clonedEmp == test: false: It means that emp and clonedEmp are two different objects, not referring to the same object. This is in agreement with the java object cloning requirement.
  2. emp and clonedEmp HashMap == test: true: So both emp and clonedEmp object variables refer to the same object. This can be a serious data integrity issue if we change the underlying object value. Any change in the value might get reflected to the cloned instance too.
  3. clonedEmp props:{city=New York, salary=10000, title=CEO}: We didn’t make any change in clonedEmp properties, but still, they got changed because both emp and clonedEmp variables are referring to the same object.This is happening because the default Object clone() method creates a shallow copy. It can be a problem when you want to create totally detached objects through cloning process. This can lead to unwanted results, hence the need to properly override the Object clone() method.
  4. clonedEmp name:Pankaj: What happened here?We changed the emp name but clonedEmp name didn’t change. It’s because String is immutable. So when we are setting emp name, a new string is created and emp name reference is changed in this.name = name;.Hence clonedEmp name remains unchanged. You will find similar behavior for any primitive variable types too. So we are good with java object default cloning as long as we have only primitive and immutable variables in the object.

Object Cloning Types

There are two types of object cloning – shallow cloning, and deep cloning. Let’s understand each of them and find out the best way to implement cloning in our Java programs.

1. Shallow Cloning

The default implementation of Java Object clone() method is using shallow copy. It’s using reflection API to create the copy of the instance. The below code snippet showcase the shallow cloning implementation.

2. Deep Cloning

In deep cloning, we have to copy fields one by one. If we have a field with nested objects such as List, Map, etc. then we have to write the code to copy them too one by one. That’s why it’s called deep cloning or deep copy.

We can override the Employee clone method like the following code for deep cloning.

With this clone() method implementation, our test program will produce the following output.

In most of the cases, this is what we want. The clone() method should return a new object totally detached from the original instance.

So if you are thinking to use Object clone and cloning in your program, do it wisely and override it properly by taking care of mutable fields.

It could be a daunting task if your class extends other class that in turn extends other class and so on. You will have to go all the way in the Object inheritance hierarchy to take care of the deep copy of all the mutable fields.

Cloning using Serialization?

One way to easily perform deep cloning is through serialization. But serialization is an expensive procedure and your class should implement Serializable interface. All the fields and superclasses must implement Serializable too.

Using Apache Commons Util

If you are already using Apache Commons Util classes in your project and your class is serializable, then use the below method.

Copy Constructor for Cloning

We can define a copy constructor to create a copy of the object. Why to depend on the Object clone() method at all?

For example, we can have an Employee copy constructor like the following code.

Whenever we need a copy of employee object, we can get it using Employee clonedEmp = new Employee(emp);.

However writing copy constructor can be a tedious job if your class has a lot of variables, especially primitive and immutable.

Java Object Cloning Best Practices

  1. Use default Object clone() method only when your class has primitives and immutable variables or you want shallow copy. In case of inheritance, you will have to check all the classes you are extending till the Object level.
  2. You can also define copy constructor if your class has mostly mutable properties.
  3. Utilize Object clone() method by calling super.clone() in overridden clone method, then make necessary changes for deep copying of mutable fields.
  4. If your class is serializable, you can use serialization for cloning. However, it will come with a performance hit, so do some benchmarking before using serialization for cloning.
  5. If you are extending a class and it has defined clone method properly using deep copy, then you can utilize default clone method. For example, we have properly defined clone() method in Employee class as follows.

    We can create a child class and utilize the superclass deep cloning as follows.

    The EmployeeWrap class doesn’t have any mutable properties and it’s utilizing superclass clone() method implementation. If there are mutable fields, then you will have to take care of deep copying of only those fields.

    Here is a simple program to test if this way of cloning works fine or not.

    Output:

    So it worked perfectly as we expected.

That’s all about Object cloning in java. I hope you got some idea about Java Object clone() method and how to properly override it without any adverse effect.

Reference: API Doc for Object clone

By admin

Leave a Reply

%d bloggers like this: