Cloning can be tricky, especially when the object's fields hold other objects. There are situations where you want to perform a deep copy, instead of only copying the field values (i.e. references to the other objects).
The bottom line is clone is broken, and you should think twice before implementing the Cloneable
interface and overriding the clone
method. The clone
method is declared in the Object
class and not in the Cloneable
interface, so Cloneable
fails to function as an interface because it lacks a public clone
method. The result is the contract for using clone
is thinly documented and weakly enforced. For example, a class that overrides clone
sometimes relies on all its parent classes also overriding clone
. They are not enforced to do so, and if they do not your code may throw exceptions.
A much better solution for providing cloning functionality is to provide a copy constructor or copy factory. Refer to Joshua Bloch's Effective Java Item 11: Override clone judiciously.