All topics
library
intermediate

Cloning: Shallow vs Deep Copy

Understand Object.clone(), its problems, and the preferred alternatives (copy constructors, factory methods).

Cloning creates a copy of an object. Java's Object.clone() creates a shallow copy: primitive fields are copied by value, but reference fields are copied by reference (both original and clone point to the same objects).

Shallow copy = photocopying a document with sticky notes. The photocopy looks the same, but the sticky notes (references) still point to the originals. If someone moves a sticky note, both documents are affected.

Key Concepts

1
Shallow copy problems: if the cloned object has mutable fields (List, Date, arrays), modifying them in the clone also modifies the original. This is rarely what you want.
2
Deep copy: recursively clone all mutable fields so the clone is completely independent. Must be done manually — Java provides no automatic deep copy.
3
Object.clone() problems: 1. Must implement Cloneable marker interface (otherwise CloneNotSupportedException) 2. clone() is protected in Object — must override as public 3. Returns Object — requires a cast (or covariant return) 4. Doesn't call constructors — can leave invariants broken 5. Doesn't work with final fields (can't reassign in clone)
4
Preferred alternatives (Effective Java Item 13): - Copy constructor: public Point(Point other) { this.x = other.x; ... } - Static factory: public static Point copyOf(Point other) { ... } - Both are clearer, don't require Cloneable, and work with final fields
5
For deep copy of complex object graphs, consider serialization-based copying or a library like Apache Commons SerializationUtils.