Q 61
Medium
What is the difference between Shallow Copy and Deep Copy in Java cloning?
Answer
A Shallow Copy duplicates the top-level object but shares references to internal nested objects. A Deep Copy creates an exact duplicate of the primary object along with recursively duplicated copies of all referenced nested objects.
Explanation
Modifying a nested mutable field in a shallow copy affects the original object. In a deep copy, both objects are completely independent.
Code Example
Java
class Address { String city; Address(String c) { this.city = c; } }
class User implements Cloneable {
String name;
Address address;
// Deep copy implementation:
public User deepCopy() {
User u = new User();
u.name = this.name;
u.address = new Address(this.address.city); // New nested copy
return u;
}
}
Reference:
Java OOP Concepts