Lesson · The Object Class & Core Contracts
Copying objects: shallow, deep, and the clone detour
16 min readCopying Objects
Assignment copies the reference; a shallow copy copies the fields and shares what they point at; a deep copy makes the referenced objects independent. Copy constructors beat Cloneable every time.
The copy that edits the original
A hand-written copy that shares the mutable parts is the quietest bug of the trio (assignment, shallow, deep):
class Team { String name; List<String> members = new ArrayList<>(); Team(Team other) { this.name = other.name; this.members = other.members; // copied the reference, not the list } } Team copy = new Team(original); copy.members.add("Dana"); System.out.println(original.members.size()); // original grew too: predict why
Predict: the constructor ran, a new Team exists, and yet adding a member to the copy changed the original. The fields were copied faithfully; members is a reference, so both teams now hold the same list. This is the shallow copy trap, and the fix is per field.
Three levels of 'copy', one table
Assignment, shallow copy and deep copy look similar in code and behave nothing alike:
| Operation | Copies | Still shared |
|---|---|---|
Team b = a; | Nothing: a second reference | The object and everything in it |
| Shallow copy (field-by-field) | The object and its field values | Every mutable object the fields point at |
| Deep copy | The object, plus referenced objects, recursively | Only what you choose to share (immutables are safe) |
There is no universal deep copy; there is a decision per field. Immutable fields (String, boxed numbers, enums, records built from immutables) are safe to share because sharing them cannot be observed. Mutable fields need a real copy or a documented promise that sharing is intended.
Copy clinic · where shallow copies bite
pick a fieldThe field
String name;
If the copy is shallow
Sharing is invisible: String is immutable, and nothing can change the text through either reference.
With the right depth
A 'deeper' copy of a String is the same String; there is nothing deeper to copy.
Immutable fields turn the depth question into a non-question.
The list, array and Date outcomes were executed with javac and java; the sizes and timestamps are real output.
The copy constructor recipe
The recommended route: a constructor that takes the same type and copies field by field, deciding each one:
Team(Team other) { this.name = other.name; // immutable: share it this.members = new ArrayList<>(other.members); // mutable: copy the container }
- Immutable fields (String, primitives, enums): assign directly; sharing them is invisible.
- Collections: copy the container (
new ArrayList<>(other.members)); the elements are shared, which is correct when they are immutable, and a decision when they are not. - Arrays:
other.scores.clone()copies the slots; the slots' contents follow the same rule as collections. - Add a static factory when a name reads better:
static Team copyOf(Team t); the mechanics are identical. - Records: nothing to do; they are immutable by construction, and copying is sharing.
Deep copying follows the field graph, one class at a time. Each class copies what it owns; if a field's class has its own copy constructor, call it. No single helper can guess the whole graph, which is exactly why clone gets it wrong (next section).
The clone detour, and why the community left it
Object.clone exists, works, and is still considered a design dead end. The reasons stack up:
- Cloneable has no methods; it toggles the behaviour of a protected method, and using it properly requires ceremony (
super.clone(), casts) that no other copy tool demands. - It returns `Object`, so every caller casts; typed alternatives (copy constructors, factories) avoid the cast and read like the rest of the language.
- It is shallow by default and silently so: the same shared-list bug hides inside a 'successful' clone.
- It cooperates badly with final fields and subclassing: correct deep cloning across a hierarchy requires cooperative overrides everywhere, which ages into archaeology.
The verdict: copy constructors and copy factories. They are typed, nameable, deep-capable per field, and they leave final fields alone; the JDK itself mostly moved on.
The copying playbook
Deciding and writing copies, in order:
- Ask why a copy exists: publishing mutable state (defensive copy), taking a snapshot, or duplicating a value. Each has an answer about which fields matter.
- For every field, classify: immutable (share), mutable owned by this object (copy), mutable shared on purpose (document it, and say who may change it).
- Write the copy constructor; add a static
copyOfif it reads better at call sites. - Copy at the boundaries: on the way in (constructor stores a copy) and on the way out (getter returns a copy) when exposing mutable internals; the encapsulation lesson's rule, made mechanical.
- Prefer fewer mutable fields overall; immutability removes the copies instead of managing them.
Assignment aliases, shallow copies half-copy, deep copies decide. The single question per field, 'can anyone observe that it is shared?', answers all three levels for the rest of your career.
A copy is a decision per field, not a keyword
Assignment shares everything; a shallow copy shares every mutable object behind the fields; a deep copy copies the field graph one class at a time. Copy constructors and static copy factories are the recommended route: typed, readable, and safe with final fields, while Cloneable stays a marker for machinery you rarely want.
Interview angles
Distinguish assignment, shallow copy and deep copy.+
Assignment copies a reference (nothing is duplicated); a shallow copy makes a new object whose fields have the same values, sharing every referenced object; a deep copy also duplicates the referenced objects, recursively.
The observable test: mutate through one handle and watch the other. Assignment and shallow copies show the change; deep copies do not, as long as every relevant level was actually copied. Immutable referenced objects make the difference invisible, which is why they are safe to share.
Team b = a; // alias: same object Team s = new Team(a); // shallow (if fields were shared) Team d = new Team(a); // deep if the constructor copies the mutable parts
Common misconception: That calling a constructor that takes another object produces a deep copy automatically. Depth is what the body does, field by field; nothing enforces it.
Follow-up: Which fields are safe to share regardless of depth?
What does a correct copy constructor look like?+
A constructor taking the same type, assigning immutable fields directly and copying mutable ones: fresh containers for collections, clones for arrays, per-field decisions throughout.
It is typed (no casts), it can set final fields, it can be as deep as needed per class, and it composes: when a field's class has its own copy constructor, call it. A static factory (copyOf) is the same mechanics with a nicer call site.
Team(Team other) { this.name = other.name; // immutable: share this.members = new ArrayList<>(other.members); // mutable: copy }
Common misconception: That copying the container is enough. It is enough exactly when the elements are immutable; otherwise each element needs its own decision.
Follow-up: Where do defensive copies belong in a class with getters?
Why is Cloneable considered broken?+
It is a marker with no methods that changes a protected method's behaviour, returns Object forcing casts, is shallow by default, and cooperates badly with final fields and subclassing.
A correct clone across a hierarchy needs cooperative super.clone() chains and careful deep copies in every subclass; miss one and the shallow bug ships silently. Copy constructors replace all of it with ordinary code that reads like ordinary code.
class Team implements Cloneable { // the ceremony begins @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); // still shallow, still Object } }
Common misconception: That clone is the standard because Object provides it. Standards moved: the community consensus for two decades has been copy constructors and factories.
Follow-up: What does super.clone() actually copy?
When is a deep copy unnecessary?+
When the referenced objects are immutable: String, boxed numbers, enums, records of immutables, and unmodifiable copies whose elements are immutable. Sharing them cannot be observed.
That is the elegant shortcut: instead of deep-copying aggressively, design more of the graph immutable. List.copyOf(other.members) for a defensive copy of the container is enough when the elements themselves never change.
this.members = List.copyOf(other.members); // container copied + locked; elements shared
Common misconception: That defensive copying means duplicating everything every time. It means duplicating exactly the mutable parts; immutables make most of the graph a non-event.
Follow-up: What does List.copyOf NOT copy?
How do defensive copies connect to encapsulation?+
They are the mechanical half of it: copy mutable state on the way in (constructor and setters) and on the way out (getters), so no caller can reach the internals.
The encapsulation lesson's reference escape, now with a toolbox: copy in, copy out, or return unmodifiable views when copying is not affordable. The choice is explicit, and the copy constructor is the tool that makes it one line.
List<String> members() { return List.copyOf(members); } // copy out
Common misconception: That returning the real list 'saves memory'. It hands every caller the internals; the saved allocation becomes an unsolvable bug report.
Follow-up: When is an unmodifiable view preferable to a copy?