Deep Copying: Cloning Referenced Objects
What you'll learn: You'll learn how to implement deep copying by recursively cloning all mutable fields, ensuring cloned objects don't share internal state with their originals.
The Problem with Shallow Copying
When you clone an object that contains references to other mutable objects, a shallow copy duplicates the references but not the objects themselves. Both the original and the clone end up pointing to the same internal objects—changes to one affect the other. This shared state defeats the purpose of cloning.
What Is Deep Copying?
Deep copying means creating independent copies of all mutable objects referenced by your class. Instead of copying references, you create brand-new instances of those objects. Think of it like photocopying a folder: shallow copying duplicates the folder but shares the same documents inside, while deep copying duplicates both the folder and all the documents.
Implementing Deep Copying
To deep copy, override clone and explicitly clone each mutable field:
@Override
public Person clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone(); // shallow copy first
// Deep copy the mutable Address field
cloned.address = this.address.clone(); // Address must also implement clone
return cloned;
}
The key is calling clone on mutable fields. This creates a chain: each referenced object must also implement deep copying for its own mutable fields, recursively ensuring complete independence.
When Fields Are Immutable
You don't need to clone immutable fields like String or Integer—shared references to immutable objects are safe because they can't be modified.
Key Takeaway: Deep copying recursively clones all mutable referenced objects to prevent shared state, ensuring the clone and original are completely independent. Each mutable field must also implement proper cloning.