源代码如下:
// A simple generic class.一个简单的泛型类
//Here ,T is a type parameter that will be replaced by a real type
//在这里,T是一个类型参数,它会被一个真正的类型所替代
//when an object of type Gen is created
//当一个Gen 类型的对象被创建的时候,
//T是一个类型参数,当一个Gen 类型的对象被创建的时候,T会被一个真正的类型所替代
class Gen<T> {
T ob;//declare an object of type T 声明一个类型为T的对象
//Pass the constructor a reference to an object of type T
//传给构造函数一个类型为的对象的引用
Gen(T o){
ob=o;
}
//return ob.返回ob
T getob(){
return ob;
}
//Show type of T. 显示T的类型
void showType(){
System.out.println("Type of T is "+ob.getClass().getName());
}
}
下面的这个类,在另外一个文件中。
//Demonstrate the generic class 演示泛型类
public class GenDemo {
public static void main(String[] args){
//Create a Gen reference for Integers.
//为Integers创建一个Gen引用
//Create a Gen <Integer> object and assign its reference to iOb.
//Notice that use of autoboxing to encapsulate the vlue 88 within an Integer objcet.
//创建一个Gen<Integer>对象,并分配它到iOb。
//注意使用自动装箱来封装值88到一个Integer对象中
Gen<Integer> iOb;
iOb=new Gen<Integer>(88);
iOb.showType();
//get the value in iOb,no cast is needed
//得到iOb中的值,不需要转换
int v =iOb.getob();
System.out.println("value:"+v);
System.out.println();
// Create a Gen object for String
//为String创建一个Gen 对象
Gen<String> strOb=new Gen<String>("Generics Tests for the String !");
strOb.showType();
String str=strOb.getob();
System.out.println("value:"+str);
}
}
补充说明一下编译器方面的情况:编译器移除了所有的泛型类型信息,进行必需的类型转换,从而使得代码的行为好像是创建了特定版本的Gen类一样。因此实际程序中,只有一个版本的Gen类。移除泛型类型信息的过程称之为擦除(erasure)。