Java Object Cloning: Shallow vs Deep Copy with clone()
Understand Java object cloning: shallow vs deep copy, implementing Cloneable correctly, common pitfalls, and practical alternatives.

When you call clone() on an object in Java, you are not guaranteed a true independent copy. For a class that implements Cloneable, the default Object.clone() performs a shallow copy; for a class that does not, it throws CloneNotSupportedException. This article explains what object cloning actually does, why it often surprises developers, and how to implement cloning that matches your requirements.
The Default Behavior of Object.clone()
Object.clone() is a protected method that creates a new instance of the same class and copies the field values from the original object. It does not invoke a constructor. For primitive fields, this copies the values directly. For reference fields, it copies the reference itself, not the object being referenced. That means both the original and the clone point to the same underlying objects.
Consider a simple class:
public class Address {
private String street;
private String city;
// constructor, getters, setters
}
public class Person implements Cloneable {
private String name;
private Address address;
// constructor, getters, setters
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}When you call person.clone(), the new Person object has the same name and the same address reference. Modifying clone.getAddress().setCity("New York") also changes the original person's address because they share the same Address instance.
Shallow Copy vs Deep Copy
The distinction between shallow and deep copy is central to cloning in Java. A shallow copy duplicates the top-level object but shares nested mutable objects. A deep copy recursively duplicates all objects reachable from the original, producing a fully independent graph.
Most real-world objects contain references to other mutable objects—collections, dates, custom classes. A shallow copy is often insufficient when the object graph is mutable and changes should not propagate between copies.
A deep copy requires explicit handling of every nested object. There is no built-in mechanism in Java that automatically deep-copies arbitrary object graphs via clone().
Implementing Cloneable Correctly
To support cloning from outside the class, implement the Cloneable marker interface and override clone() with public access. Because Object.clone() is protected, a protected override cannot be called by code in other packages.
@Override
public Person clone() {
try {
Person cloned = (Person) super.clone();
cloned.address = this.address.clone(); // requires Address to expose a usable clone()
return cloned;
} catch (CloneNotSupportedException e) {
throw new AssertionError("Cannot clone Person", e);
}
}Every mutable reference field must be explicitly cloned. If Address does not implement Cloneable, you need another way to copy it, such as a copy constructor. If a mutable field can be null, add a null check before cloning it.
The CloneNotSupportedException is a checked exception, but when the class implements Cloneable, it should not be thrown for a direct call. Many developers wrap it in an AssertionError or another runtime exception to keep the method signature clean.
Common Pitfalls with Cloneable
The Cloneable interface is notoriously easy to misuse. Here are the most frequent issues:
- Forgetting to call
super.clone(): The base implementation does the field-by-field copy. If you construct a new object manually, you lose the shallow copy behavior and may break invariants. - Not cloning final fields:
clone()cannot assign new values tofinalfields. If a class has afinalreference to a mutable object, the clone will share that object, and you cannot replace it without reflection or a different approach. - Subclassing complications: When a superclass implements
Cloneable, subclasses inherit it. If a subclass adds mutable fields, itsclone()must handle them, or it will silently produce a shallow copy. - Arrays: Arrays have a built-in
clone()that performs a shallow copy of the array elements. For an array of objects, the elements are shared. To deep-copy an array, you must clone each element. - Collections: The default collection classes like
ArrayListandHashMapimplementCloneablebut only shallow-copy their contents. The contained objects are still shared.
These pitfalls often lead to subtle bugs that are hard to trace because the code compiles and runs without errors.
Alternatives to clone(): Copy Constructors and Factories
Because Cloneable is error-prone, many Java developers prefer copy constructors or static factory methods. A copy constructor is a constructor that takes an instance of the same class and creates a new one with copied state.
public Person(Person other) {
this.name = other.name;
this.address = new Address(other.address); // assuming Address has a copy constructor
}This approach gives you full control over the copying process. It works with final fields, does not require Cloneable, and is type-safe. The downside is that you must write a copy constructor for every class that needs copying, and you must manually handle nested objects.
A static factory method can be used similarly:
public static Person copyOf(Person original) {
return new Person(original);
}These alternatives are often clearer than clone() because they make the copying logic explicit and avoid the checked exception.
Using Serialization for Deep Copy
Serialization can perform a deep copy if your object graph is fully serializable. The idea is to write the object to a byte stream and then read it back, creating a new object graph.
public static <T> T deepCopy(T object) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(object);
}
try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) {
return (T) ois.readObject();
}
}This approach works for any object that implements Serializable, including nested objects. However, it has significant drawbacks:
- Performance: Serialization is often much slower than manual copying because it involves reflection and I/O operations.
- Transient fields: Fields marked
transientare not serialized and will be lost in the copy. - Static fields: Static fields are not part of the serialized state, so static state is shared rather than copied.
- Not all classes are serializable: External or legacy classes may not implement
Serializable. - Security: Deserialization can be a vector for attacks if the data is not trusted.
Use serialization-based cloning only when the object graph is complex, and performance is not critical.
Performance and Maintainability Considerations
Manual deep copying with copy constructors is explicit, type-safe, and does not rely on reflection. The cost is writing boilerplate code, but the clarity often outweighs the effort.
Object.clone() performs the shallow part without running a constructor, so it can be slightly faster in some cases, but the difference is usually not important for applications. The real cost is writing and maintaining the deep-copy logic on top of it. If performance matters, measure it in your actual application.
Serialization-based cloning is often much slower than manual copying and creates a dependency on Serializable. Avoid it in performance-sensitive paths unless you have measured the cost and found it acceptable.
For maintainability, copy constructors and static factories are easier to read and modify. They do not require the class to implement a marker interface, and they work with final fields.
Choosing the Right Cloning Strategy
The choice depends on your specific requirements:
- Use the
clone()pattern when you need a shallow copy and the class is under your control. Be prepared to override it for every subclass and handle nested mutable objects manually. - Use copy constructors when you need deep copies and want explicit, readable code. This is the most predictable approach for most business objects.
- Use serialization when you have a deeply nested object graph and cannot write manual copy logic, or when you need a generic deep-copy utility. Accept the performance cost.
If you are working with immutable objects, cloning is unnecessary. Reuse the same instance instead of copying it.
For collections, consider using the copyOf static methods introduced in Java 10 for unmodifiable copies, or manually copy elements if you need a mutable deep copy. The copyOf methods duplicate the collection itself, not the objects inside it.
Handling Final Fields and Immutable References
One of the trickiest aspects of cloning is dealing with final fields. Because clone() creates a new object via super.clone(), the final fields are already set to the same references as the original. You cannot reassign them in the clone() method. If the final field points to a mutable object, the clone will share it.
A copy constructor does not have this limitation. You can assign new values to final fields in the constructor body, as long as they are assigned exactly once. This makes copy constructors the only clean way to deep-copy objects with final mutable references.
Consider a class like this:
public final class Configuration {
private final List<String> allowedHosts;
public Configuration(List<String> allowedHosts) {
this.allowedHosts = new ArrayList<>(allowedHosts);
}
public Configuration(Configuration other) {
this.allowedHosts = new ArrayList<>(other.allowedHosts);
}
}The copy constructor creates a new list, so the copy is independent. Using clone() would not allow this because allowedHosts is final.
A Practical Example: Deep Copying a Composite Object
Let's put the concepts together with a complete example. Suppose you have an Order that contains a list of LineItem objects, each with its own Product reference. A deep copy should duplicate the order, the list, and each line item, but the Product might be immutable and can be shared.
public class Product {
private final String sku;
private final String name;
// constructor, getters
}
public class LineItem {
private Product product;
private int quantity;
// constructor, getters, setters
public LineItem(LineItem other) {
this.product = other.product; // immutable, safe to share
this.quantity = other.quantity;
}
}
public class Order {
private List<LineItem> items;
public Order(List<LineItem> items) {
this.items = new ArrayList<>(items);
}
public Order(Order other) {
this.items = new ArrayList<>();
for (LineItem item : other.items) {
this.items.add(new LineItem(item));
}
}
}This copy constructor creates a new Order with a new list and new LineItem objects, but shares the immutable Product references. That is a correct deep copy for this object graph. If Product were mutable, it would need to be copied as well.
If you used Object.clone(), you would need to override clone() in Order and LineItem, handle the list cloning manually, and ensure LineItem implements Cloneable. The copy constructor approach is simpler and less error-prone.
The Role of Immutability in Cloning
Immutability changes the cloning decision entirely. If an object and all its dependencies are immutable, sharing is safe. Cloning becomes unnecessary because there is no risk of unintended mutation. This is why modern Java code favors immutable value objects, often implemented with records.
When you design a class, consider whether it truly needs to be cloneable. Often, you can avoid cloning by making the object immutable or by using builder patterns that create new instances with modified state.
If you must support cloning, prefer copy constructors over Cloneable for new code. The Cloneable interface is a legacy feature that does not provide a clone() method declaration—it is merely a marker. The actual method comes from Object, and its behavior is often misunderstood.
By understanding the mechanics of Java object cloning, you can choose the approach that fits your data model and avoid the subtle bugs that come from shallow copies.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.