Cloning in Java

In this post, we will learn about Cloning in Java with an example.

What is Cloning in Java ?

Cloning is a way to create an exact copy of an object. Object class in Java provides a method clone(), that generates a duplicate copy of the object on which it is called. The syntax of clone() method is as below.

Syntax of clone() method:

this method creates and returns a copy of this object.

If we want to create a clone of an object, then the class must implement java.lang.Cloneable interface. If we don’t implement Cloneable interface, clone() method throws CloneNotSupportedException. When a clone is made, the constructor for the object being cloned is not called. If we change the content in 

Example:

Output:

If you observe the output, we have cloned the object cloningDemo into the object cloningDemo1. After cloning we have got the same Name and Age in object cloningDemo1, which we have set in the object cloningDemo.

Other tutorials:

Reflection in Java

Related posts

Leave a Comment