Java Reference
In-Depth Information
Display 13.8
Implementation of the Method clone (Harder Case)
1
public class
YourCloneableClass2
implements
Cloneable
2 {
3
private
DataClass someVariable;
4 .
5 .
6 .
7
public
Object clone()
8 {
9
try
10 {
11 YourCloneableClass2 copy =
12 (YourCloneableClass2)super.clone();
13 copy.someVariable = (DataClass)someVariable.clone();
14
DataClass
is a mutable class. Any other
instance variables are each of a primitive
type or of an immutable type like
String
.
return
copy;
15 }
16
catch
(CloneNotSupportedException e)
17 {
//This should not happen.
18
return null
;
//To keep the compiler happy.
19 }
20 }
21 .
22 .
23 .
24 }
If the clone method return type is
DataClass
rather
than
Object
, then this type cast is not needed.
The class
DataClass
must also properly implement
the
Cloneable
interface including dei ning the
clone
method as we are describing.
someVariable
. So, the reference is replaced by a reference to a copy of the object
named by
someVariable
. This is done with the following line:
3
copy.someVariable = (DataClass)someVariable.clone();
The object named by
copy
is now safe and so can be returned by the
clone
method.
If there are more instance variables that have a mutable class type, then you repeat
what we did for
someVariable
for each of the mutable instance variables.
This requires that the class type
DataClass
has a correctly working
clone
method
that is marked
public
, but that will be true if the class type
DataClass
implements
the
Cloneable
interface in the way we are now describing. That is,
DataClass
should
implement the
Cloneable
interface following the model of Displays 13.7 or 13.8 ,
3
Depending on how the
clone
method was defined in the class
DataClass
, the type cast may or
may not be needed, but causes no harm in any case.