Object cloning is a way to create an exact copy of an object. The clone()
method of an object class is used to clone an object.
Cloning can also be done using an assignment operator (e.g., object2 = object1) but this will never create a new object. An assignment operator will help object2 point to the location of object1, but any changes in object2 will be reflected in object1. This issue is solved by the clone()
method that creates a new object and lets the two objects remain independent.
The following slides will help you understand the key difference between the assignment operator and the clone
method:
clone()
methodIt allows two objects to exist independently, despite being copies of one another.
Cloning is the fastest way to copy objects.
If we use a copy constructor, then we have to copy all of the data over explicitly, however, cloning copies data automatically.
The following example shows the cloning of an object:
class objects implements Cloneable { int num; public Object clone() throws CloneNotSupportedException { return super.clone(); } } // Driver class class Main { public static void main(String args[]) throws CloneNotSupportedException { objects object1=new objects();//creating object1 object1.num=5;//setting object1's num = 5 objects object2=new objects();//creating object2 //display object1's num System.out.println("Initially Object1's num is : " + object1.num); //Creating a cloned object objects clonedObject=(objects)object1.clone(); clonedObject.num=10;//changing cloned object's num System.out.println("After cloning Object1's num is : " + object1.num); object2=object1; //using assignment operator object2.num=10; //changing object2's num //display object1's num System.out.println("After assignment operator Object1's num is : " + object1.num); } }
RELATED TAGS
View all Courses