Java Reference
In-Depth Information
This may seem surprising if you thought that Cell<String> was a class.
But it is only Cell that is a class. The use of <String> and <Integer> in the
constructor invocations are not class definitions. They declare informa-
tion about the type of object being constructed so that the compiler can
check that the object is used correctly. At runtime, no generic type in-
formation is present in objects. In the example above, the Cell object
that contains the element "Hello" has no knowledge that it was con-
structed as a Cell<String> that knowledge has been erased; a concept we
come back to a bit later in the chapter (see page 267 ) .
The fact that there is a single class definition for a generic class, no mat-
ter how many different parameterized invocations there may be, has
several consequences in regard to what you can and cannot do with
generics. We point these out along the way, but they all boil down to
this: There is only one class, so you cannot do anything that cannot be
done with only one class.
The first consequence of this fact is that a generic class with a type
parameter, say E , cannot use E in the type of a static field or anywhere
within a static method or static initializer. To do so would require a dif-
ferent field or method for each value of E . Because there is only one
class, there is only one actual static field or method, and so the code
cannot depend on the value of E . The fact that static members are
never dependent on a particular parameterization is reinforced by the
rule that you cannot refer to a static member via a parameterized type
name. For example, if SingleLinkQueue has a static merge method, it must
be invoked as SingleLinkQueue.merge . SingleLinkQueue<Integer>.merge , for
example, would not compile. To similarly reinforce that there is but a
single class object, a class literal such as SingleLinkQueue.class can only
use the raw class name.
Within a generic class definition, a type parameter can appear in any
non-static declaration where you would normally put a concrete type
name: in a field declaration, a method return type or parameter type
declaration, a local variable declaration, or a nested type declaration.
You've
seen
examples
of
most
of
these
uses
in
the Cell and
SingleLinkQueue classes.
 
Search WWH ::




Custom Search