What is clone() method in Java?
Object cloning refers to creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
Using Assignment Operator to create copy of reference variable
In Java, there is no operator to create copy of an object. Unlike C++, in Java, if we use assignment operator then it will create a copy of reference variable and not the object.
Creating a copy using clone() method
The class whose object’s copy is to be made must have a public clone method in it or in one of its parent class.
Every class that implements clone() should call super.clone() to obtain the cloned object reference.
- The class must also implement java.lang.Cloneable interface whose object clone we want to create otherwise it will throw CloneNotSupportedException when clone method is called on that class’s object.
- Syntax: protected Object clone() throws CloneNotSupportedException
protected Object clone throws CloneNotSupportedException
Advantages of clone method:
If we use assignment operator to assign an object reference to another reference variable then it will point to same address location of the old object and no new copy of the object will be created. Due to this any changes in reference variable will be reflected in original object.
If we use copy constructor, then we have to copy all of the data over explicitly i.e. we have to reassign all the fields of the class in constructor explicitly. But in clone method this work of creating a new copy is done by the method itself. So to avoid extra processing we use object cloning.