Last Updated:

Cloning objects in Java. Example of using the clone() method

To use cloning in Java, you need to implement the interface , otherwise an exception will be thrown.

java.lang.CloneableCloneNotSupportedException

Let's take a look at the Java class below:

The result is the following output to the console:

From the results of the program execution, it can be seen that the standard implementation of the method uses a partial copy and ct2 depends on any changes in the attributes of ct1, so we must override the method .

clone()clone()

 

Cloning objects in Java

Important Note on Object Cloning in Java

If your class contains mutable objects, then you need to ensure that the method executes properly using deep copying. Uncomment the method and run the program again.
Now the result will be as follows:

clone()clone()

Now both objects do not affect each other and cloning works correctly.