In Java cloning, a shallow copy creates a new object but shares references to nested objects with the original instance. A deep copy, however, creates a completely independent duplicate by copying both the object and all objects it references. The choice between the two depends on whether changes to the cloned object should affect the original object.
Key Points: • A shallow copy duplicates only the top-level object, while referenced objects remain shared between the original and the clone. • A deep copy recursively copies all nested objects, ensuring complete independence between the original and copied objects. • The clone() method typically performs a shallow copy by default, so additional logic is required to implement deep copying.
Example: Consider an Employee object containing an Address object. With a shallow copy, both Employee objects reference the same Address. If the address changes in one object, the change is visible in the other. With a deep copy, each Employee has its own Address object, so changes remain isolated.
Code Example:
class Address {
String city;
Address(String city) {
this.city = city;
}
}
class Employee implements Cloneable {
String name;
Address address;
Employee(String name,
Address address) {
this.name = name;
this.address = address;
}
@Override
protected Object clone()
throws CloneNotSupportedException {return super.clone(); // Shallow Copy
}
}Interview Tip: A concise interview answer is: A shallow copy creates a new object but shares references to nested objects with the original, whereas a deep copy creates completely independent copies of both the object and all referenced objects. By default, clone() performs a shallow copy, and custom logic is needed for deep cloning.