X Y Z T Coordinates:
6 8 14 8
22 9 4 9
3 -2 -23 17
Notice these commented-out lines:
showXYZ(tdlocs); // Error, not a ThreeD
showAll(tdlocs); // Error, not a FourD
Because tdlocs is a Coords(TwoD) object, it cannot be used to call showXYZ( ) or
showAll( ) because bounded wildcard arguments in their declarations prevent it. To prove
this to yourself, try removing the comment symbols, and then attempt to compile the
program. You will receive compilation errors because of the type mismatches.
In general, to establish an upper bound for a wildcard, use the following type of wildcard
<? extends superclass>
where superclass is the name of the class that serves as the upper bound. Remember, this is an
inclusive clause because the class forming the upper bound (that is, specified by superclass) is
also within bounds.
You can also specify a lower bound for a wildcard by adding a super clause to a wildcard
declaration. Here is its general form:
<? super subclass>
In this case, only classes that are superclasses of subclass are acceptable arguments. This is an
exclusive clause, because it will not match the class specified by subclass.
Creating a Generic Method
As the preceding examples have shown, methods inside a generic class can make use of a
class' type parameter and are, therefore, automatically generic relative to the type parameter.
However, it is possible to declare a generic method that uses one or more type parameters
of its own. Furthermore, it is possible to create a generic method that is enclosed within a
non-generic class.
Let's begin with an example. The following program declares a non-generic class called
GenMethDemo and a static generic method within that class called isIn( ). The isIn( ) method
determines if an object is a member of an array. It can be used with any type of object and
array as long as the array contains objects that are compatible with the type of the object
being sought.
// Demonstrate a simple generic method.
class GenMethDemo {
// Determine if an object is in an array.
static <T, V extends T> boolean isIn(T x, V[] y) {
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks