Java Reference
In-Depth Information
mented out. The first three calls are valid because
w
,
w2
, and
w3
are
Gen
objects whose
type is either
A
or a subclass of
A
. However, the last call to
test( )
is illegal because
w4
is
an object of type
D
, which is not derived from
A
. Thus, the bounded wildcard in
test( )
will
not accept
w4
as an argument.
In general, to establish an upper bound for a wildcard, use the following type of wildcard
expression:
<? extends
superclass
>
Ask the Expert
Q
:
Can I cast one instance of a generic class into another?
A
:
Yes, you can cast one instance of a generic class into another, but only if the two are
otherwise compatible and their type arguments are the same. For example, assume a
generic class called
Gen
that is declared like this:
Next, assume that
x
is declared as shown here:
Then, this cast is legal
because
x
is an instance of
Gen<Integer>
. But, this cast
is not legal because
x
is not an instance of
Gen<Long>
.