Cloning object and Cloneable interface in java.

Bavatharany Mahathevan
2 min readJan 24, 2022

In this article, we are going to discuss the overview of cloning an object in java.

Cloning object refers to creating an exact copy of an existing object rather than creating a new object with a new keyword and passing the same parameters to the particular constructor to create the same instance.

So, we can save the extra processing task when we use the clone() method.

Java provides us with the facility to create a copy of an object by the clone() method.

The clone() method is a method of the Object class. Hence, Everybody can use and override the clone method as well.

The syntax of clone() is given below.

@IntrinsicCandidateprotected native Object clone() throws CloneNotSupportedException;

Even though, in order to use the clone() method to make an exact copy of the object of an existing object, we have to :

  • implement the Cloneable interface.
  • define the clone() method and call the super.clone()
  • handle the CloneNotSupportedException.
  • call the clone() on the existing object

Let's see a small example for cloning an object

output:

java
java

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

We can create a copy of an object in two ways.

  1. Shallow copy
  2. Deep copy

A shallow copy is one way to copy of values of the object’s fields only. This is the default cloning method. As both objects refer to the same reference, the original and cloned object are not independent. When we modify an object, the change will be reflected on other objects.

Deep copy is the opposite way of shallow copy. Both objects are fully independent. Here, the new memory location is allocated for the new cloned object rather than reference. So, both objects are fully independent. The change on one object will not be reflected on other objects.

Reference:

https://www.edureka.co/blog/cloning-in-java/

--

--