This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Cloneable is broken.
Posted by Kent Spaulding on June 08, 1999 at 8:38 AM
You heartily recommend implementing Cloneable in all
classes; but the clone() method is broken to the point
of being useless.
First, it says nothing about the copy semantics. Is it
deep or shallow?
Second, it is protected in Object, and hence requires the
VM to do an exceptional thing, relax the accessor to make
clone() public in a subclass. That's ugly design.
Third, implementing clone() is problematic. As you suggest,
for all mutable fields that are Cloneable (requires an
expensive instanceof check, especially for fields that are
interface types) you must call clone(). However, you may get a
CloneNotSupportedExecption. It makes no sense whatsoever for
a class to claim that it is Cloneable, but not be. Unfortunately,
classes can do this.
The lack of meaningful semantics in at least two cases, makes
clone() an abomination to be avoided. Avoid clone() and use
Serializable exclusively for deepCopy semantics.