Deep and shallow cloning are techniques used to create copies of objects. In shallow cloning, the object itself is copied, but any referenced objects are shared between the original and the clone. In deep cloning, both the object and all objects it references are duplicated, creating completely independent copies. The Cloneable interface acts as a marker interface that indicates a class supports cloning through the clone() method.
Key Points: • Shallow cloning copies primitive values and object references, causing nested objects to be shared. • Deep cloning creates separate copies of all nested objects, ensuring complete independence. • A class must implement Cloneable and override clone() to avoid CloneNotSupportedException.
Example: Consider an Employee object that contains an Address object. In shallow cloning, both Employee objects refer to the same Address. If the address changes in one object, it changes for the other. In deep cloning, each Employee gets its own Address copy.
Code Example:
class Address implements Cloneable {
String city;
Address(String city) {
this.city = city;
}
@Override
protected Address clone()
throws CloneNotSupportedException {
return (Address) super.clone();
}
}
class Employee implements Cloneable {
String name;
Address address;Employee(String name,
Address address) {
this.name = name;
this.address = address;
}
@Override
protected Employee clone()
throws CloneNotSupportedException {
Employee cloned =
(Employee) super.clone();
// Deep Clone
cloned.address =
address.clone();
return cloned;
}
}
public class Main {
public static void main(String[] args)
throws Exception {
Employee emp1 =
new Employee(
"John",
new Address("Pune"));
Employee emp2 =
emp1.clone();
emp2.address.city = "Mumbai";
System.out.println(
emp1.address.city);
System.out.println(
emp2.address.city);
}
}Interview Tip: A concise interview answer is: Shallow cloning copies an object while sharing references to nested objects, whereas deep cloning creates independent copies of both the object and its referenced objects. The Cloneable interface marks a class as cloneable, and the clone() method must be overridden to define whether cloning should be shallow or deep.