Java Reference
In-Depth Information
Note:
A collection can clone the objects that a client adds to it, but you will have duplicates
of each entry in the collection. For complex objects, the time and memory needed to make
each copy can be substantial.
30.32
Realize that some devious programming could defeat the purpose of our sorted list of clones. You
could write a
clone
method that retains a reference to the clone. Then, knowing when a sorted list
calls
clone
, you could get and retain the reference to the clone. Restricting the contents of a collection
to immutable objects is a safer way to maintain its integrity.
C
HAPTER
S
UMMARY
•
An object that belongs to a class having public mutator (set) methods is mutable because the client can use
the methods to change the values of the object's data fields. If a client cannot change the values of an
object's data fields, the object's class is read only, and the object is immutable.
•
A read-only class is final, has private data fields that, if mutable, are final, and has no public set methods.
•
Companion classes represent the same data in both immutable and mutable forms.
•
The class
Object
includes a protected method
clone
that makes an identical copy of an object. A class can
override
clone
and declare it public, thus making it available to a client of the class. Such a class must imple-
ment the Java interface
Cloneable
. If a class does not override
clone
, it has no
clone
method, since
clone
is
protected in
Object
.
•
A
clone
method should invoke
super.clone()
to ensure that all aspects of an object are copied.
•
Every array has a
clone
method that copies the array but not the objects in it. A separate step is necessary to
clone these objects.
•
To create a deep clone of a chain of linked nodes, you must clone the nodes, including their data objects.
P
ROGRAMMING
T
IPS
•
Use an immutable object if it will be shared or added to a collection that can be corrupted by changes to the
object. Use a mutable object if its data will change frequently.
•
Not all classes should have a public
clone
method. In fact, most classes, including read-only classes, do not
have one.
•
If your program produces the exception
CloneNotSupportedException
even though you implemented a
method clone in your class, you probably forgot to write
implements
Cloneable
in your class definition.
•
Every public
clone
method must invoke the method
clone
of the base class by executing
super.clone
.
Ultimately,
Object
's protected
clone
method will be invoked. That invocation must appear in a
try
block,
even though a
CloneNotSupportedException
will never occur.
•
Shallow copies of data fields that reference immutable objects are typically sufficient for a clone. Sharing an
immutable object is usually safe.
•
When bounding generic types, use an interface that declares a public method
clone
instead of using
Cloneable
. The new interface must extend
Cloneable
, however.