Clone() Method in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

Suppose we have created an object and now we want a copy of same object with all its member functions and data members, without wasting compilation time. Writing same code takes space as well as time therefore that can be done using the clone() method in Java used for object cloning in java. So, to create the exact copy of an object we use the clone() method in java. But wait how do we do that? Well, read the complete article to understand it in detail.

Syntax of clone() in Java

The syntax for clone() in Java looks something like this:

Parameters of clone() in Java

The clone() method does not accept any parameters.

Return Values of clone() in Java

  • We all know what is the work of the return function in any language, the same goes here it returns the copy of the object, hence the return type is object.
  • If a java.lang.The cloneable interface is not implemented then it will throw CloneNotSupportedException.
  • Moreover, object clone is a protected method so we have to override it.

Example of clone() in Java

In this example, we will print the sides of the triangle twice by using the cloneable interface.

Flow of the code

In the above example, we have implemented a cloneable interface and then made a method named copy(). To not get the error CloneNotSupportedException should be thrown we add throws CloneNotSupportedException from the method copy() that we made.

We have created sides of a triangle and assigned values to them by creating an object and to get a copy of that object an instance is made i.e., show()that displays the values assigned to the integer values.

Try catch block is implemented. In the try block, we are calling the copy function, since the copy function is returning a new cloned object it will get in t2, the show is called with a new cloned object. In case of any error, the code will jump to catch block and will display the error message

Output

We can see from the output that the line is repeated twice and it is because we have created the clone() method for the object Triangle.

clone() Method in Java

There are times when we have to use the same code in our program but rewriting the same code makes our program bulky as well as time-consuming. But Java saves us from it by providing the excellent feature i.e., clone() method in java that is used to create an exact copy of the object. The clone() method belongs to java.lang.Object class.

Cloning doesn't mean that every detail is copied, it simply means copying the object properties and having different references with the same contents.

Well, this might be a lot, but we got you. In the next section, we will be understanding what we did.

There are some steps that are required to work with clone() method.

  1. To use the clone method in Java, the class must implement a cloneable method.
  2. To call the cloned object, the class that implements the clone method must call super.clone().
  3. If the cloneable interface is not implemented CloneNotSupportedException has created else the object clone that we want to create of a particular class must implement java.lang.Cloneable interface.

In the above example, we first created an object.clone. Let us see what happens if we don't implement the Triangle class as cloneable also the copy method does not throw CloneNotSupportedException.

The code will look something like this.

Result It will throw the following error.

More Examples:

Let us understand the clone() method in java with different examples.

  • Creating a copy using the clone() method.
  • Changing value using the cloned object.

Creating a Copy Using the clone() Method

To make an object's copy the class or one of the parent classes must have a public clone method in it.

The java.lang.Cloneable interface should be implemented by the class otherwise it will throw CloneNotSupportedException when the clone() method will be called.

Syntax

For example

Result

To create a copy we have used obj.clone() method. We have defined a constructor and made an instance that will display our values which are name and id.

Changing Value Using Cloned Object

Let us see an example where we will change the value of the object using the cloned object.

Example:

In the following example, we have the name and age of a person and we want to change the age of the person using a clone in the cloned object.

Output

As we can see, the value of age is changed using the clone() method.

Java Shallow Copy

Shallow cloning defines the cloning process done by invoking the clone() method. It is a default cloning process. The work it does is shallow copy the original object with the exact field. If the original object is referenced to some other objects then the reference of that object is copied. In simple words, if the value of the cloned object is changed then it will show it in the original object too if it has any referenced data type, not in the case of int or char.

Let's understand it with an example:

Example:

In this example, we will be taking two integer values and changing the values in the referenced object and we will see if the changed values are reflected in the other objects.

Output

When we try to change the value of the copied data the change is reflected in the original object too. Therefore when we changed the value of the reference it is reflected in the original. Changes in references of objects are not copied while primitive data types are copied. From the above example, we see that clone of S1 returns the shallow copy of the object S1.

Java Deep Copy

In a deep copy, the exact copy of the original object is made. If the original object has a reference to other objects, then the clone copy is made for the referenced object. The changes made in the reference object are not reflected in the original object. This shows that deep cloning is independent of the original object.

Example:

In this example, we will change the value of the referenced object and check whether the value is changed in the original object using the deep cloning method.

Output

In the main function, the instance is created where the values are defined. If there are any changes they are reflected only in the referenced object because a constructor is created outside the main function that iterated through the values. From the above example, we can see that the value remains unchanged in R2.z.l and R2.x.

Conclusion

  • Clone() method in java is used to create a copy of the object.
  • To implement the clone method we should implement the Cloneable interface otherwise it will throw a CloneNotSupportedException error.
  • Clone method is divided into two categories - Shallow cloning and Deep Cloning.
  • The key difference between shallow and deep cloning is: Shallow cloning is dependent on the original object while deep cloning is independent of the original object which means the changes in a referenced variable in the case of deep copy don't reflect.