Java Reference
In-Depth Information
TIP: Use a Type Parameter Bound for a Better
clone
★
One way to overcome the problem discussed in the previous Pitfall section is to place a
bound on the type parameter
T
(in Display 15.12) so that it must satisfy some suitable
interface. There is no standard interface that does the job, but it is very easy to define
such an interface. The interface
PubliclyCloneable
given in Display 15.13 is just the
interface we need. This short, simple interface guarantees all that we need to define
generic linked lists whose clone method returns a deep copy.
Note that any class that implements the
PubliclyCloneable
interface has the fol-
lowing three properties:
1. The class implements the
Cloneable
interface. (This happens automatically because
PubliclyCloneable
extends
Cloneable
.)
2. The class has a public
clone
method.
3. The
clone
method for the class makes a deep copy (in the officially sanctioned way).
Condition 3 is not enforced by the Java compiler or run-time software, but like all
interface semantics, it is the responsibility of the programmer defining the class to
ensure that condition 3 is satisfied.
It is now easy to define our generic linked list whose
clone
method produces a deep
copy. The definition is given in Display 15.14. We have already discussed the main
points involved in this definition. The following Programming Example subsection
discusses some of the minor, but possibly unclear, details of the definition.
1
■
1
Display 15.13
The
PubliclyCloneable
Interface
1
/*
2
The programmer who defines a class implementing this interface
3
has the responsibility to define clone so it makes a deep copy
4
(in the officially sectioned way.)
5
*/
6
public
interface
PubliclyCloneable
extends
Cloneable
7{
8
public
Object clone( );
9}
Any class that implements
PubliclyCloneable
automatically
implements
Cloneable
.
Any class that implements
PubliclyCloneable
must have a
public
clone
method.
1
You might wonder whether we could use a type parameter in the
PubliclyCloneable
interface and
so avoid some type casts in the definition
copyOf
. We could do that, but that may be more trouble
than it is worth and, at this introductory level of presentation, would be an unnecessary distraction.