Course contentsShow
← Java
Lesson 564 of 2,87013. The Object Class and Common MethodsFree lesson

Shallow Copy Problem: Shared References

Discover how shallow copies share references to mutable objects, causing unintended side effects.

Shallow Copy Problem: Shared References

What you'll learn: You'll discover how shallow copies can cause unexpected bugs when copied objects share mutable references.


When you use the default clone() method from Object, you get a shallow copy—a new object whose fields are copied directly from the original. This works perfectly for primitive values and immutable objects, but creates a serious problem with mutable object references.

The Core Issue

A shallow copy duplicates the reference itself, not the object it points to. Both the original and the clone end up pointing to the same underlying object in memory. If either one modifies that shared object, the change appears in both copies—often when you least expect it.

Why This Happens

Think of it like photocopying a document that contains someone's phone number. The copy has the same phone number written on it, but both copies refer to the same person. If that person changes their address, you'll reach the same updated address from either copy of the document.

In Java terms, when you clone an object containing an array or ArrayList field, the clone gets a copy of the reference variable, but both variables point to the same array or list in the heap.

The Consequence

Imagine you clone a Person object that has an Address field. After cloning, modifying the clone's address actually modifies the original person's address too—because they share the same Address object. This violates the expectation that cloning creates an independent copy.

Key Takeaway: Shallow copying shares references to mutable objects between the original and clone, causing unintended side effects when those shared objects are modified through either reference.