Java Reference
In-Depth Information
derived class, you should invoke the
clone
method of the base class
Object
(or what-
ever the base class is) and then reset the values of any new instance variables whose
types are mutable class types. You reset these instance variables to copies of the
instance variables in the calling object. There are also issues of exception handling to
deal with. An example may be clearer than an abstract discussion.
Let's start with the simple case. Suppose your class has no instance variables of a
mutable class type, or to phrase it differently, suppose your class has instance variables
all of whose types are either a primitive type or an immutable class type, like
String
.
And to make it even simpler, suppose your class has no specified base class, so the base
class is
Object
. If you want to implement the
Cloneable
interface, you should define
the
clone
method as in Display 13.7.
The
try-catch
blocks are required because the inherited method
clone
can throw the
exception
CloneNotSupportedException
if the class does not correctly implement
the
Cloneable
interface. Of course, in this case the exception will never be thrown, but
the compiler will still insist on the
try-catch
blocks.
Now let's suppose your class has one instance variable of a mutable class type
named
DataClass
. Then, the definition of the
clone
method should be as in Display
13.8. First a bit-by-bit
copy
of the object is made by the invocation of
super.clone()
.
The dangerous part of
copy
is the reference to the mutable object in the instance
Display 13.7
Implementation of the Method
clone
(Simple Case)
1
public class
YourCloneableClass
implements
Cloneable
2{
3
Works correctly if each instance variable is of a
primitive type or of an immutable type like
String
.
.
4
.
5
.
6
public
Object clone()
7
{
8
try
9
{
10
return super
.clone();
//Invocation of clone
11
//in the base class Object
12
}
13
catch
(CloneNotSupportedException e)
14
{
//This should not happen.
15
return null
;
//To keep the compiler happy.
16
}
17
}
18
.
19
.
20
.
21
}