Video in progress
Why are `Cloneable` and `clone()` called bad design, and what are better ways to copy an object?
Cloneable is a marker interface with no methods that quietly changes the behavior of Object.clone(). clone() bypasses constructors, makes a shallow copy, throws a checked exception, and doesn't work with final fields. Use a copy constructor or a static factory instead.
📖 Answer
The problems with clone():
- The
Cloneableinterface has noclone()method. It only signals thatObject.clone()is "allowed", which goes against the usual meaning of an interface. Object.clone()isprotectedand throwsCloneNotSupportedException(checked), so every override hastry/catchnoise.- The constructor isn't called: validation and invariants in the constructor are bypassed.
- A shallow copy: a
List, array or other mutable object inside is shared with the original. For a deep copy you have to reassign the field, but you can't assign a new value to afinalfield insideclone(). - The inheritance chain: every class must call
super.clone()correctly, and if one of them does anew, the whole mechanism breaks.
Better options:
public final class Draft {
private final String title;
private final List<String> tags;
public Draft(Draft other) { // copy constructor
this(other.title, other.tags);
}
public Draft(String title, List<String> tags) {
this.title = title;
this.tags = List.copyOf(tags); // an immutable copy (shallow, but Strings are immutable anyway), and validation runs
}
public static Draft copyOf(Draft d) { return new Draft(d); }
}
What is good about it: it goes through the constructor, it works with final fields, there is no exception, and it can accept an interface type (like new ArrayList<>(anyCollection)).
Immutable objects don't need copying at all: sharing one instance is safe. For arrays, array.clone() is still a normal and short option, which is an exception to this rule.
Sign up to mark studied questions and save your progress.