The term generics means parameterized types.
(Java 2 V5.0 (Tiger) New Features by Herbert Schildt )
- T is a type parameter that will be replaced by a real type.
- 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.
class GenericClass<T> {
T ob;
GenericClass(T o) {
ob = o;
}
T getob() {
return ob;
}
void showType() {
System.out.println("Type of T is " + ob.getClass().getName());
}
}
public class MainClass {
public static void main(String args[]) {
// Create a Gen reference for Integers.
GenericClass<Integer> iOb = new GenericClass<Integer>(88);
iOb.showType();
// no cast is needed.
int v = iOb.getob();
System.out.println("value: " + v);
// Create a Gen object for Strings.
GenericClass<String> strOb = new GenericClass<String>("Generics Test");
strOb.showType();
String str = strOb.getob();
System.out.println("value: " + str);
}
}
Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test