Java Reference
In-Depth Information
The output is shown here:
Although most aspects of this program should be easy to understand, a couple of key
points need to be made. First, notice that Containment is declared like this:
In general, a generic interface is declared in the same way as a generic class. In this case,
the type parameter T specifies the type of objects that are contained.
Next, Containment is implemented by MyClass . Notice the declaration of MyClass ,
shown here:
In general, if a class implements a generic interface, then that class must also be generic, at
least to the extent that it takes a type parameter that is passed to the interface. For example,
the following attempt to declare MyClass is in error:
This declaration is wrong because MyClass does not declare a type parameter, which
means that there is no way to pass one to Containment . In this case, the identifier T is
simply unknown and the compiler reports an error. Of course, if a class implements a spe-
cific type of generic interface, such as shown here:
then the implementing class does not need to be generic.
As you might expect, the type parameter(s) specified by a generic interface can be
bounded. This lets you limit the type of data for which the interface can be implemented.
For example, if you wanted to limit Containment to numeric types, then you could declare
it like this:
Search WWH ::




Custom Search