Default clone Behavior: Shallow Copying
You'll learn what happens when you call Object.clone() and why it only copies the "surface" of an object.
What Is Shallow Copying?
When you call clone() on an object that implements Cloneable, Java performs a field-by-field copy. For primitive fields (like int, boolean, char), this works perfectly—the values are duplicated. But for reference fields (objects, arrays), Java only copies the reference itself, not the object being referenced.
Think of it like photocopying a document that contains a phone number. You get a duplicate document with the same phone number written on it, but both copies point to the same phone line. If someone changes that phone's voicemail, both "copies" reflect the change because they share the underlying resource.
How Shallow Copying Works
class Address {
String city;
Address(String city) {
this.city = city;
}
}
class Person implements Cloneable {
String name;
Address address; // Reference field
Person(String name, Address address) {
this.name = name;
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
When you clone a Person, the name String reference is copied, but more importantly, the address reference is copied—not the Address object itself. Both the original and clone share the same Address instance.
The Problem Illustrated
Person original = new Person("Alice", new Address("NYC"));
Person copy = (Person) original.clone();
copy.address.city = "Boston"; // Modifies shared Address!
System.out.println(original.address.city); // Prints "Boston" — unexpected!
Key Takeaway: Object.clone() performs shallow copying: primitives are duplicated, but reference fields in the original and clone point to the same objects, creating unexpected shared state.