Object Cloning in Java: Create Exact Copies of Objects
Learn how to clone objects in Java using the clone()
method from the Object class. Understand the importance of implementing the Cloneable
interface in your class to enable cloning and how to handle CloneNotSupportedException
when the interface is not implemented.
Object Cloning in Java
Object cloning is a way to create an exact copy of an object. The clone()
method of the Object class is used for this purpose.
The java.lang.Cloneable
interface must be implemented by the class whose object we want to clone. If not, the clone()
method throws CloneNotSupportedException
.
Syntax of the clone()
method:
protected Object clone() throws CloneNotSupportedException
Why use clone()
method?
The clone()
method saves the extra processing needed to create an exact copy of an object using the new
keyword.
Advantages of Object Cloning
- Saves writing lengthy and repetitive code.
- Easiest and most efficient way to copy objects, especially in old projects.
- Fastest way to copy arrays.
Disadvantages of Object Cloning
- Requires changes to syntax: implementing
Cloneable
, definingclone()
, and handlingCloneNotSupportedException
. - The
Cloneable
interface has no methods, just indicates the ability to clone. Object.clone()
is protected, so we must provide our ownclone()
method.Object.clone()
doesn't invoke any constructor, so we have no control over object construction.- Supports only shallow copying; we must override for deep cloning.
Example of clone()
method
Syntax
class Student18 implements Cloneable {
int rollno;
String name;
Student18(int rollno, String name) {
this.rollno = rollno;
this.name = name;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String args[]) {
try {
Student18 s1 = new Student18(101, "amit");
Student18 s2 = (Student18) s1.clone();
System.out.println(s1.rollno + " " + s1.name);
System.out.println(s2.rollno + " " + s2.name);
} catch (CloneNotSupportedException c) {
c.printStackTrace();
}
}
}
Output
101 amit
101 amit
In the example above, both reference variables have the same values. The clone()
method copies the values of an object to another object.
If we create another object using the new
keyword and assign the values, it will require a lot of processing. To save this processing, we use the clone()
method.