Java Reference
In-Depth Information
Notice that its parameter, o , is of type T . This means that the actual type of o is determined
by the type passed to T when a Gen object is created. Also, because both the parameter o
and the member variable ob are of type T , they will both be of the same actual type when
a Gen object is created.
The type parameter T can also be used to specify the return type of method, as is the case
with the getob( ) method, shown here:
Because ob is also of type T , its type is compatible with the return type specified by getob(
) .
The showType( ) method displays the type of T . It does this by calling getName( ) on
the Class object returned by the call to getClass( ) on ob . We haven't used this feature
before, so let's examine it closely. As you should recall from Chapter 7 , the Object class
defines the method getClass( ) . Thus, getClass( ) is a member of all class types. It returns
a Class object that corresponds to the class type of the object on which it is called. Class is
a class defined within java.lang that encapsulates information about a class. Class defines
several methods that can be used to obtain information about a class at run time. Among
these is the getName( ) method, which returns a string representation of the class name.
The GenDemo class demonstrates the generic Gen class. It first creates a version of Gen
for integers, as shown here:
Look carefully at this declaration. First, notice that the type Integer is specified within the
angle brackets after Gen . In this case, Integer is a type argument that is passed to Gen 's
type parameter, T . This effectively creates a version of Gen in which all references to T
are translated into references to Integer . Thus, for this declaration, ob is of type Integer ,
and the return type of getob( ) is of type Integer .
Before moving on, it's necessary to state that the Java compiler does not actually create
different versions of Gen , or of any other generic class. Although it's helpful to think in
these terms, it is not what actually happens. Instead, the compiler removes all generic type
information, substituting the necessary casts, to make your code behave as if a specific ver-
Search WWH ::




Custom Search