Java Reference
In-Depth Information
signed to
v
(which is an
int
). Thus, there is no need to cast the return type of
getob( )
to
Integer
.
Next,
GenDemo
declares an object of type
Gen<String>
:
Because the type argument is
String
,
String
is substituted for
T
inside
Gen
. This creates
(conceptually) a
String
version of
Gen
, as the remaining lines in the program demonstrate.
Generics Work Only with Reference Types
When declaring an instance of a generic type, the type argument passed to the type para-
meter must be a reference type. You cannot use a primitive type, such as
int
or
char
. For
example, with
Gen
, it is possible to pass any class type to
T
, but you cannot pass a primit-
ive type to
T
. Therefore, the following declaration is illegal:
Of course, not being able to specify a primitive type is not a serious restriction because you
can use the type wrappers (as the preceding example did) to encapsulate a primitive type.
Further, Java's autoboxing and auto-unboxing mechanism makes the use of the type wrap-
per transparent.
Generic Types Differ Based on Their Type Arguments
A key point to understand about generic types is that a reference of one specific version of
a generic type is not type-compatible with another version of the same generic type. For
example, assuming the program just shown, the following line of code is in error and will
not compile:
Even though both
iOb
and
strOb
are of type
Gen<T>
, they are references to different
types because their type arguments differ. This is part of the way that generics add type
safety and prevent errors.
A Generic Class with Two Type Parameters
You can declare more than one type parameter in a generic type. To specify two or more
type parameters, simply use a comma-separated list. For example, the following
TwoGen
class is a variation of the
Gen
class that has two type parameters: