Java Reference
In-Depth Information
Since
super.clone()
returns an instance of
Object
, we must cast this instance to
Name
. After all,
we are creating a
Name
object as the clone. The
return
statement will implicitly cast
theCopy
to
Object
, as required.
The exception that
Object
's method
clone
can throw is
CloneNotSupportedException
. Since
we are writing a
clone
method for our class
Name
, this exception will never occur. Even so, we still
must use
try
and
catch
blocks when invoking
Object
's
clone
method. Instead of the
println
statement in the
catch
block, we could write the simpler statement
throw new
Error(e.toString());
Programming Tip:
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
CloneNotSupported
-
Exception
will never occur.
30.16
Two ways to copy.
What does this method
clone
actually do? You want it to make copies of the data
fields associated with the invoking object. When a data field is an object, you can copy it in one of
two ways:
•
You can copy the reference to the object and share the object with the clone, as illustrated in
Figure 30-4a. This copy is called a
shallow copy
; the clone is a
shallow clone
.
•
You can copy the object itself, as illustrated in Figure 30-4b. This copy is called a
deep copy
;
the clone is a
deep clone
.
Note:
Object
's
clone
method returns a shallow clone.
FIGURE 30-4
(a) A shallow clone; (b) a deep clone
(a)
Data field
Data field
Data
An object
The object's shallow clone
(b)
Data field
Data field
Data
Cloned data
An object
The object's deep clone
30.17
Name
's clone is shallow.
The class
Name
has the data fields
first
and
last
, which are instances of
String
. Each field contains a reference to a string. It is these references that are copied when
clone
invokes
super.clone()
. For example, Figure 30-5 illustrates the objects that the following state-
ments create:
Name april =
new
Name("April", "Jones");
Name twin = (Name)april.clone();
The clone
twin
is a shallow clone because the strings that are the first and last names are not copied.