Cloning means creating a copy of the object. There is a way that we can create an exact copy of an object which is known as object cloning. To clone an object we use clone() method which is coming from Object class. Here we have to implement Clonable interface by the class whose object clone we want to create. If we are not trying to implement Cloneable interface, clone() method generates CloneNotSupportedException.
Let's see demo program on objet clonig for better clarity.
As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another. If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.❮ Previous Next ❯