Writing Generic Classes
Now that we have (at least some of) the “end user” view of generics, let’s try writing a few classes ourselves. In this section, we’ll talk about how type variables are used in the definition of generic classes, where they may appear, and some of their limitations. We’ll also talk about subclassing generic types.
The Type Variable
We’ve already seen the basics of how type variables are used in the declaration of a generic class. One or more type variables are declared in the angle bracket (<>) type declaration and used throughout the body and instance methods of the class. For example:
classMouse{}classBear{}classTrap<T>{Ttrapped;publicvoidsnare(Ttrapped){this.trapped=trapped;}publicTrelease(){returntrapped;}}// usageTrap<Mouse>mouseTrap=newTrap<Mouse>();mouseTrap.snare(newMouse());Mousemouse=mouseTrap.release();
Here, we created a generic Trap
class that can hold any type of object. We used the type variable
T to declare an
instance variable of the parameter type as well as in the argument type
and return type of the two methods.
The scope of the type variable is the instance portion of the class, including methods and any instance initializer blocks. The static portion of the class is not affected by the generic parameterization, and type variables are not visible in static methods or static initializers. As you might guess, just as all instantiations of the generic type have only one actual class (the raw type), ...