Object cloning in Java is the process of creating an exact copy of an existing object. It is used when you need a duplicate object without manually copying all attributes.
How to Clone an Object in Java
Java provides the clone()
method in the Object
class to achieve cloning.
Steps for Cloning an Object
- Implement the
Cloneable
interface (preventsCloneNotSupportedException
). - Override the
clone()
method in your class. - Call
super.clone()
inside the overriddenclone()
method.
1. Example of Shallow Copy (Default Cloning)
A shallow copy creates a new object, but its fields still reference the same objects.
class Person implements Cloneable { // without Cloneable, CloneNotSupportedException
String name;
Person(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // Performs shallow copy
}
}
public class ShallowCloneExample {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person("Alice");
Person p2 = (Person) p1.clone(); // Clone p1 into p2
System.out.println(p1.name); // Alice
System.out.println(p2.name); // Alice
p2.name = "Bob"; // Change p2's name
System.out.println(p1.name); // Alice (original remains unchanged)
}
}
✅ Here, p1
and p2
are different objects, but the fields are copied.