Java Reference
In-Depth Information
30.18
Example: Creating a deep clone of a single field.
Sometimes a shallow clone is unsuitable. If a
class has mutable objects as data fields, you must clone the objects and not simply copy their refer-
ences. For example, let's add a method
clone
to the class
Student
that we encountered in Segment C.2
of Appendix C. The class has the following form after we add the required
implements
clause:
public class
Student
implements
Cloneable
{
private
Name fullName;
private
String id;
< Constructors and the methods
setStudent
,
setName
,
setId
,
getName
,
getId
, and
toString
>
. . .
}
// end Student
Since the class
Name
has set methods, the data field
fullName
is a mutable object. Therefore, we
should be sure to clone
fullName
within the definition of
Student
's
clone
method. We can do that
because we added a
clone
method to
Name
in Segment 30.15. Since
String
is read only,
id
is immutable,
and so cloning it is unnecessary. Thus, we can define a
clone
method for the class
Student
as follows:
public
Object clone()
{
Student theCopy =
null
;
try
{
theCopy = (Student)
super
.clone();
// Object can throw an exception
}
catch
(CloneNotSupportedException e)
{
throw new
Error(e.toString());
}
theCopy.fullName = (Name)fullName.clone();
return
theCopy;
}
// end clone
After invoking
super.clone()
, we clone the mutable data field
fullName
by calling
Name
's public
clone
method. This latter invocation need not be within a
try
block. Only
Object
's
clone
method
contains a
throws
clause.
Figure 30-7 illustrates an instance of
Student
and the clone that this method returns. As you
can see, the
Name
object that represents the student's full name is copied, but the strings that repre-
sent the first and last names, as well as the ID number, are not.
FIGURE 30-7
An instance of
Student
and its clone, including a deep copy of
fullName
"Kim"
first
last
first last
fullName
fullName
"Lo"
"1234"
id
id
The clone
s.clone()
An instance
s
of
Student