Java Reference
In-Depth Information
object that is returned. Note that the overriding implementation de-
clares that it returns an instance of
MyClass
, not
Object
, utilizing the abil-
ity to specify a covariant return typethis saves the calling code from
having to supply a cast, but we have to supply it internally when return-
ing the value from
super.clone()
.
The
clone
method in
Object
has a
throwsCloneNotSupportedException
de-
claration. This means a class can declare that it can be cloned, but a
subclass can decide that it can't be cloned. Such a subclass would im-
plement the
Cloneable
interface because it extends a class that does so,
but the subclass could not, in fact, be cloned. The extended class would
make this known by overriding
clone
to always throw
CloneNotSuppor-
tedException
and documenting that it does so. Be carefulthis means that
you cannot determine whether a class can be cloned by a run time check
to see whether the class implements
Cloneable
. Some classes that can't
be cloned will be forced to signal this condition by throwing an excep-
tion.
3.9.2. Correct Cloning
Objects of most classes can be cloned in principle. Even if your class
does not support the
Cloneable
interface, you should ensure that its
clone
method is correct. In many classes, the default implementation of
clone
will be wrong because it duplicates a reference to an object that
shouldn't be shared. In such cases,
clone
should be overridden to be-
have correctly. The default implementation assigns each field from the
source to the same field in the destination object.
If, for example, an object has a reference to an array, a clone of one
of the objects will refer to the same array. If the array holds read-only
data, such a shared reference is probably fine. But if it is a list of objects
that should be distinct for each of your objects, you probably don't want
the clone's manipulation of its own list to affect the list of the original
source object, or vice versa.
Here is an example of the problem. Suppose you have a simple integer
stack class: