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;
DataClass
is a mutable class. Any other
instance variables are each of a primitive
type or of an immutable type like
String
.
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
return
copy;
15
}
16
catch
(CloneNotSupportedException e)
17
{
//This should not happen.
18
return null
;
//To keep the compiler happy.
19
}
20
}
If the clone method return type is
DataClass
rather
than
Object
, then this type cast is not needed.
21
.
22
.
23
.
24
}
The class
DataClass
must also properly implement
the
Cloneable
interface including defining the
clone
method as we are describing.
variable
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 Display 13.7 or Display 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.