Why this matters
- The aliasing bug this causes is among the hardest to trace: you copy an object, change the copy, and the original changes too.
Cloneableis one of the JDK's acknowledged design mistakes, and knowing why is more useful than knowing how to use it.- Defensive copying is the practical skill underneath all of it, and it protects encapsulation at every API boundary.
input.add(pen) is visible to the caller. input = new Cart() is not — it only repoints the copy.
Shallow versus deep
| Aspect | Shallow copy | Deep copy |
|---|---|---|
| New top-level object | Yes | Yes |
| Nested mutable objects | Shared with the original | Also duplicated |
| Independence | Only for primitive and immutable fields | Complete |
| Cost | Cheap | Proportional to the object graph |
| Safe when | Every field is primitive or immutable | Always |
New top-level object
Shallow copyYesDeep copyYesNested mutable objects
Shallow copyShared with the originalDeep copyAlso duplicatedIndependence
Shallow copyOnly for primitive and immutable fieldsDeep copyCompleteCost
Shallow copyCheapDeep copyProportional to the object graphSafe when
Shallow copyEvery field is primitive or immutableDeep copyAlways
A shallow copy is perfectly correct when nothing it points at can change.
How clone() actually works
Object.clone() is protected and native. It allocates a new object of the same class and copies
every field bit for bit — references included. To expose it you must do two things that look
arbitrary.
Why this is considered broken
Cloneabledeclares no methods. It is a marker that changes the behaviour of aprotectedmethod on a different class — a mechanism found nowhere else in the language.clone()bypasses constructors. No validation runs, andfinalfields cannot be assigned, so invariants you rely on may not hold.- It throws a checked exception you cannot encounter. Every implementation needs the unreachable catch block above.
- It is shallow by default, in a method whose name implies otherwise.
- Subclasses inherit the problem. Any subclass adding a mutable field silently gets a broken clone unless it overrides again.
For a deep clone you must fix up each mutable field yourself:
Every mutable field must be remembered. Adding a field later and forgetting this method is the standard way this breaks months after it was written.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 3 sections
- Better ways to copy
- Defensive copying at the boundary
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.