// Demonstrate the generic class.
class GenDemo {
public static void main(String args[]) {
// Create a Gen reference for Integers.
Gen<Integer> iOb;
// Create a Gen<Integer> object and assign its
// reference to iOb.  Notice the use of autoboxing
// to encapsulate the value 88 within an Integer object.
iOb = new Gen<Integer>(88);
// Show the type of data used by iOb.
iOb.showType();
// Get the value in iOb. Notice that
// no cast is needed.
int v = iOb.getob();
System.out.println("value: " + v);
System.out.println();
// Create a Gen object for Strings.
Gen<String> strOb = new Gen<String>("Generics Test");
// Show the type of data used by strOb.
strOb.showType();
// Get the value of strOb. Again, notice
// that no cast is needed.
String str = strOb.getob();
System.out.println("value: " + str);
}
}
The output produced by the program is shown here:
Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test
Let's examine this program carefully.
First, notice how Gen is declared by the following line:
class Gen<T> {
Here, T is the name of a type parameter. This name is used as a placeholder for the actual
type that will be passed to Gen when an object is created. Thus, T is used within Gen whenever
the type parameter is needed. Notice that T is contained within < >. This syntax can be
generalized. Whenever a type parameter is being declared, it is specified within angle
brackets. Because Gen uses a type parameter, Gen is a generic class, which is also called a
parameterized type.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home