Shallow Copy
A shallow copy creates a new object, but it does not create copies of nested objects —instead, it copies references to them. This means if you modify the nested object inside one copy, it affects the original.
Example of a Shallow Copy:
class Student implements Cloneable {
String name;
Address address; // Nested object
Student(String name, Address address) {
this.name = name;
this.address = address;
}
// Clone method (Shallow Copy)
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Address {
String city;
Address(String city) {
this.city = city;
}
}
public class ShallowCopyExample {
public static void main(String[] args) throws CloneNotSupportedException {
Address addr1 = new Address("Mumbai");
Student student1 = new Student("Raj", addr1);
// Cloning student1 (Shallow Copy)
Student student2 = (Student) student1.clone();
student2.address.city = "Delhi"; // Changes original object too!
System.out.println(student1.address.city); // Output: Delhi
System.out.println(student2.address.city); // Output: Delhi
}
}
Key Point: Changes made to
student2.address.city
also reflect in
student1
, because both share the same reference to
Address
.
Deep Copy
A deep copy creates a new object and also creates new copies of all nested objects. This ensures that modifications in one copy do not affect the original.
Example of a Deep Copy:
class Student implements Cloneable {
String name;
Address address; // Nested object
Student(String name, Address address) {
this.name = name;
this.address = new Address(address.city); // Deep Copy
}
// Custom deep copy method
public Student deepClone() {
return new Student(name, new Address(address.city));
}
}
class Address {
String city;
Address(String city) {
this.city = city;
}
}
public class DeepCopyExample {
public static void main(String[] args){
Address addr1 = new Address("Mumbai");
Student student1 = new Student("Raj", addr1);
// Creating a deep copy manually
Student student2 = student1.deepClone();
student2.address.city = "Delhi"; // Doesn't affect student1
System.out.println(student1.address.city); // Output: Mumbai
System.out.println(student2.address.city); // Output: Delhi
}
}
Key Point: Changes made to
student2.address.city
do NOT
affect
student1
since a completely new object is created.
Comparison Table
Feature | Shallow Copy | Deep Copy |
---|---|---|
Copies object itself | ||
Copies nested objects | (Keeps reference) | (Creates new copies) |
Changes in nested objects affect the original | ||
Memory Usage | Less | More |
When to Use What?
- Shallow Copy is faster and requires less memory but can cause unintended side effects when modifying nested objects.
- Deep Copy provides complete independence between copies but is slower and requires more memory.