Java Reference
In-Depth Information
3.9. Cloning Objects
The
Object.clone
method helps you write
clone
methods for your own
classes. A clone method returns a new object whose initial state is a copy
of the current state of the object on which
clone
was invoked. Subse-
quent changes to the new clone object should not affect the state of the
original object.
3.9.1. Strategies for Cloning
There are three important factors in writing a
clone
method:
•
The empty
Cloneable
interface, which you must implement to
[3]
Cloneable
should have been spelled
Clonable
, but the misspelling was realized too late to
be fixed.
•
The
clone
method implemented by the
Object
class, which per-
forms a simple clone by copying all fields of the original object to
the new object. This method works for many classes but may need
to be supplemented by an overriding method.
•
The
CloneNotSupportedException
, which can be used to signal that a
class's
clone
method shouldn't have been invoked.
A given class can have one of four different attitudes toward
clone
:
•
Support
clone
. Such a class implements
Cloneable
and declares its
clone
method to throw no exceptions.
•
Conditionally support
clone
. Such a class might be a collection
class that can be cloned in principle but cannot successfully be
cloned unless its contents can be cloned. This kind of class will im-
plement
Cloneable
, but will let its
clone
method pass through any