In Java, cloning is a process of creating an exact copy of an object. It is useful when you want a new object with the same state as an existing object, but one that is independent of the original object.
- The clone() method creates a copy of an object.
- The class must implement the Cloneable interface; otherwise, clone() throws a CloneNotSupportedException.
Types of Cloning in Java
There are two types of cloning or copying in Java, mentioned below:
1. Shallow Cloning
Shallow cloning in Java creates a new object, but the new object that is created has the same reference as the original object, so instead of creating an actual copy, it involves copying the references.
Shallow cloning is done by calling super.clone() method as default implementation of the clone is present in the Object class.
Java
class Student implements Cloneable{
int id;
String name;
Student(int id, String name){
this.id = id;
this.name = name;
}
// Overriding clone() method
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public void display(){
System.out.println("ID: " + id + ", Name: " + name);
}
}
public class GFG{
public static void main(String[] args){
try {
Student s1 = new Student(101, "John");
Student s2 = (Student) s1.clone(); // cloning
s1.display();
s2.display();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
OutputID: 101, Name: John
ID: 101, Name: John
Explanation:
- Student implements Cloneable to allow cloning.
- clone() is overridden to call super.clone(), which performs a shallow copy.
- Primitive fields (int id) are copied, but if there were object references, both objects would share the same reference.
- Shallow cloning is fast and simple but may lead to unintended side effects if shared references are modified.
Note: Changes to primitive fields in the cloned object do not affect the original. However, changes to referenced objects will reflect in both.
2. Deep Cloning
Deep cloning creates a copy of an object along with all the objects it references, ensuring complete independence from the original object. Unlike shallow cloning, changes in the original object's referenced objects do not affect the cloned object.
Java
class Address implements Cloneable {
String city;
String state;
Address(String city, String state)
{
this.city = city;
this.state = state;
}
// Overriding clone() for deep copy
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
class Student implements Cloneable{
int id;
String name;
Address address; // nested object
Student(int id, String name, Address address){
this.id = id;
this.name = name;
this.address = address;
}
// Overriding clone() for deep copy
public Object clone() throws CloneNotSupportedException{
Student cloned = (Student)super.clone();
cloned.address
= (Address)
address.clone(); // cloning nested object
return cloned;
}
public void display()
{
System.out.println("ID: " + id + ", Name: " + name
+ ", City: " + address.city
+ ", State: " + address.state);
}
}
public class DeepCloneDemo {
public static void main(String[] args){
try{
Address addr = new Address("New York", "NY");
Student s1 = new Student(101, "John", addr);
// Deep cloning
Student s2 = (Student)s1.clone();
// Modify original object's address
s1.address.city = "Los Angeles";
// Display both objects
s1.display();
s2.display();
}
catch (CloneNotSupportedException e){
e.printStackTrace();
}
}
}
OutputID: 101, Name: John, City: Los Angeles, State: NY
ID: 101, Name: John, City: New York, State: NY
Explanation:
- Student contains a nested object Address.
- In clone(), the nested object is also cloned manually to create a deep copy.
- Modifying s1.address.city does not affect s2, showing that both objects are independent.
- Deep cloning is more complex but necessary when objects contain mutable nested references.
Rules for Cloning in Java
- The class must implement Cloneable; otherwise, clone() throws CloneNotSupportedException.
- Override the clone() method from the Object class.
- Decide whether a shallow or deep copy is required based on the object’s structure.
Advantages of Cloning
- Performance: Faster than creating a new object and setting all fields manually.
- Convenience: Easy duplication of complex objects.
- Polymorphism support: Works with objects of unknown types at runtime.
Shallow Cloning vs Deep Cloning
The table below demonstrates the difference between shallow cloning and deep cloning.
Aspect | Shallow Cloning | Deep Cloning |
|---|
Mutable objects | It shares the same references | It creates independent copies of referenced objects |
|---|
Object Reference | It only copies the reference, not the object. | It recursively copies all referenced objects |
|---|
Complexity | It is simpler and faster | It is more complex and slower because of recursive copying. |
|---|
Use Case | Suitable when shared objects are acceptable and does not require modification of objects. | Used when full independence between original and clone is required |
|---|
Default Behaviour | Object's clone() performs shallow cloning by default | Requires manual handling (overriding clone()) for deep cloning |
|---|
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java