Java Reference
In-Depth Information
of the object, but it can't be declared
final
because its value needs to
be explicitly set in
clone
.
If the object that should not be shared between the clone and the origin-
al, is not an array, that object should support copying in some way. That
may mean that the object itself supports
clone
, or that it has a
copy con-
structor
that allows a duplicate object to be created. For example, the
String
class does not support
clone
but it does have a copy constructor
that creates a new
String
with the same contents as the
String
passed
to the constructor. The issues when writing copy constructors are the
same as those for writing
clone
you must decide when a simple field copy
is sufficient and when more specific action is required. One advantage
the copy constructor has is that it can deal with
final
fields in situations
where
clone
cannot.
Sometimes making
clone
work correctly is not worth the trouble, and
some classes should not support
clone
. In such cases, you should define
a
clone
method that throws
CloneNotSupportedException
so that objects
with bad state will never be created by an unsuspecting subclass that
uses
clone
.
You can declare that all subclasses of a class must support
clone
prop-
erly by overriding your class's
clone
method with one that drops the
declaration of
CloneNotSupportedException
. Subclasses implementing the
clone
method cannot throw
CloneNotSupportedException
, because methods
in a subclass cannot add an exception to a method. In the same way, if
your class makes
clone
public, all extended classes must also have pub-
lic
clone
methods, because a subclass cannot make a method less visible
than it was in its superclass.
3.9.3. Shallow versus Deep Cloning
The default implementation of clone provides what is known as a
shallow
clone or copyit simply performs a field by field copy. A
deep
clone would
clone each object referred to by a field and each entry in an array. This
would apply recursively and so deep cloning an object would clone all of
the objects reachable from that object. In general,
clone
is overridden to