Final Fields and clone: The Conflict
What You'll Learn
You'll discover why final fields create a fundamental problem when implementing deep copy in clone methods.
The Core Problem
When you declare a field as final, you promise Java that the field will be assigned exactly once—either at declaration or in the constructor. But here's the conflict: the clone method doesn't call constructors. It creates an object using super.clone(), which copies field values directly.
For shallow copying, this works fine. But when you need a deep copy, you must reassign reference fields to point to newly cloned objects. And that's where final collides with clone: you cannot reassign a final field after the object is created.
The Conflict in Action
Imagine a class with a final array field:
public class Portfolio implements Cloneable {
private final int[] holdings; // final!
public Portfolio(int[] holdings) {
this.holdings = holdings;
}
@Override
public Portfolio clone() throws CloneNotSupportedException {
Portfolio copy = (Portfolio) super.clone();
// ERROR: Cannot assign to final field
copy.holdings = holdings.clone(); // Won't compile!
return copy;
}
}
The compiler rejects this because holdings is final. But without that reassignment, copy and the original share the same array—a shallow copy that defeats the purpose of cloning.
The Impossible Choice
You must choose:
- Keep
final: Accept shallow copying with shared references (often unacceptable) - Remove
final: Enable deep copying but lose immutability guarantees
This is a design flaw in Java's clone mechanism. Modern alternatives like copy constructors or static factory methods don't have this limitation.
Key Takeaway:
final fields cannot be reassigned in clone, making deep copying impossible without removing final—a fundamental incompatibility between immutability and Java's cloning mechanism.