Java Reference
In-Depth Information
11.1. Generic Type Declarations
The declaration of the class Cell<E> is an example of a generic type de-
claration. It declares Cell to be a generic class, where the type variable
E is known as the type parameter of the generic declaration. When you
use a type name such as Cell<String> , providing a specific type argument
( String ) to replace the generic type parameter ( E ), you thereby introduce
a parameterized type. This has some similarities to the method invoca-
tion process where declared parameters are given the values of specific
arguments, so the use of a parameterized type such as Cell<String> is
also known as a generic type invocation.
A generic type declaration can contain multiple type parameters, separ-
ated by commas. For example, the Map interface (see page 587 ) defines
a generic mapping between keys and values so it is declared as inter-
faceMap<K, V> , where K is the type parameter for the key type and V is the
type parameter for the value type.
When you define a generic class, all invocations of that generic class
are simply expressions of that one class. Declaring a variable strCell as
Cell<String> tells the compiler that strCell will refer to an object of type
Cell<E> where E will be String . It does not tell the compiler to create a new
class Cell<String> . Cell<String> and Cell<Number> are not two separate
classes. They are two generic type invocations of the one class Cell that
are applied in two different ways to two different objects. The class Cell
is known as the raw type corresponding to the generic class declaration
Cell<E> .
The following code shows quite clearly that there is just one class be-
cause the value of same is TRue :
Cell<String> strCell = new Cell<String>("Hello");
Cell<Integer> intCell = new Cell<Integer>(25);
boolean same = (strCell.getClass() == intCell.getClass());
 
Search WWH ::




Custom Search