Java Reference
In-Depth Information
Bounded types are especially useful when you need to ensure that one type parameter
is compatible with another. For example, consider the following class called Pair , which
stores two objects that must be compatible with each other:
Notice that Pair uses two type parameters, T and V , and that V extends T . This means
that V will either be the same as T or a subclass of T . This ensures that the two arguments
to Pair 's constructor will be objects of the same type or of related types. For example, the
following constructions are valid:
However, the following is invalid:
In this case, String is not a subclass of Number , which violates the bound specified by
Pair .
Using Wildcard Arguments
As useful as type safety is, sometimes it can get in the way of perfectly acceptable con-
structs. For example, given the NumericFns class shown at the end of the preceding sec-
tion, assume that you want to add a method called absEqual( ) that returns true if two
NumericFns objects contain numbers whose absolute values are the same. Furthermore,
Search WWH ::




Custom Search