clone() Method - Object Cloning in Java
Object cloning in Java refers to creating an exact copy of an object. The clone() method in Java is used to clone an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
Example 1: Here is a simple example demonstrating object cloning using the clone() method in Java.
// Java program to demonstrate object cloning
// using the clone() method
class GFG implements Cloneable {
int x, y;
// Constructor to initialize
// object fields
GFG() {
x = 10;
y = 20;
}
// Overriding the clone() method
@Override
public Object clone() throws CloneNotSupportedException {
// Returning a clone of the current object
return super.clone();
}
}
public class Main {
public static void main(String[] args)
throws CloneNotSupportedException {
GFG o1 = new GFG();
// Cloning obj1 into obj2
GFG o2 = (GFG) o1.clone();
System.out.println("o1: " + o1.x + " " + o1.y);
System.out.println("o2: " + o2.x + " " + o2.y);
}
}
Output
o1: 10 20 o2: 10 20
Syntax of clone() Method
protected Object clone() throws CloneNotSupportedException
- Return Type: It returns an Object type, which is a reference to the cloned object.
- Exception: It throws a CloneNotSupportedException if the object's class does not implement the Cloneable interface.
Example 2: Simple Object Cloning (Shallow Copy)
Here, we clone a simple object i.e. the shallow copy using the clone() method.
// Java program to demonstrate
// object cloning (shallow copy)
class GFG implements Cloneable {
String n;
int a;
// Constructor to initialize GFG object
public GFG(String n, int a) {
this.n = n;
this.a = a;
}
// Overriding clone() method
// to make it public
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "GFG{name:'" + n + "', age:" + a + '}';
}
}
public class Main {
public static void main(String[] args) {
try {
// Create a Person object
GFG p1 = new GFG("Ram", 24);
// Clone the Person object
GFG p2 = (GFG) p1.clone();
// Print both objects
System.out.println("Original: " + p1);
System.out.println("Cloned: " + p2);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Output
Original: GFG{name:'Ram', age:24} Cloned: GFG{name:'Ram', age:24}
Explanation: In the above example, the clone() method is overridden in the GFG class to perform a shallow copy of the object. This creates a new object "p2" with the same values as the original object "p1", but changes to immutable fields like String do not affect each other.
Example 3: Deep Copy with Object Cloning
Here, we demonstrate deep cloning by manually cloning referenced objects.
// Java program to demonstrate
// deep copy using clone()
// An object reference of this
// class is contained by Test2
class Test {
int x, y;
}
// Contains a reference of Test and
// implements clone with deep copy.
class Test2 implements Cloneable {
int a, b;
Test c = new Test();
public Object clone() throws CloneNotSupportedException
{
// Assign the shallow copy to
// new reference variable t
Test2 t = (Test2)super.clone();
// Creating a deep copy for c
t.c = new Test();
t.c.x = c.x;
t.c.y = c.y;
// Create a new object for the field c
// and assign it to shallow copy obtained,
// to make it a deep copy
return t;
}
}
public class Main {
public static void main(String args[])
throws CloneNotSupportedException
{
Test2 t1 = new Test2();
t1.a = 10;
t1.b = 20;
t1.c.x = 30;
t1.c.y = 40;
Test2 t3 = (Test2)t1.clone();
t3.a = 100;
// Change in primitive type of t2 will
// not be reflected in t1 field
t3.c.x = 300;
// Change in object type field of t2 will
// not be reflected in t1(deep copy)
System.out.println(t1.a + " " + t1.b + " " + t1.c.x
+ " " + t1.c.y);
System.out.println(t3.a + " " + t3.b + " " + t3.c.x
+ " " + t3.c.y);
}
}
Output
10 20 30 40 100 20 300 40
Explanation: In the above example, we can see that a new object for the Test class has been assigned to copy an object that will be returned to the clone method. Due to this, t3 will obtain a deep copy of the object t1. So any changes made in the ācā object fields by t3, will not be reflected in t1.
Advantages of the clone() Method
- If we use the assignment operator to assign an object reference to another reference variable then it will point to the same address location of the old object and no new copy of the object will be created. Due to this any changes in the reference variable will be reflected in the original object.
- If we use a copy constructor, then we have to copy all the data over explicitly i.e. we have to reassign all the fields of the class in the constructor explicitly. But in the clone method, this work of creating a new copy is done by the method itself. So to avoid extra processing we use object cloning.
Note: We can use the Assignment Operator to create a copy of the reference variable. This creates a shallow copy, means both variables will refer to the same object in memory. This is not the same as cloning, where a new object is created.