此为说明泛型的一般用法:可以让程序员少写某些代码,而且可以也是其主要目的:解决类型安全问题(如向上转型和向下转型),它提供了编译时的安全检查。
下面的代码经本人测试,望对Java泛型类型不解的人有所帮助。
/**
* It is a general example of the application of the overclass(泛型)。
* <p>
* 此为说明泛型的一般用法:可以让程序员少写某些代码,
* 而且可以也是其主要目的:解决类型安全问题(如向上转型和向下转型),它提供了编译时的安全检查。
* @author HAN
*
* @param <T>
*/
public class OverClassApps3<T> {
private T b;
public T getB(){
return b;
}
public void setB(T b){
this.b=b;
}
public static void main(String[] args){
OverClassApps3<Boolean> test1=new OverClassApps3<Boolean>();
OverClassApps3<Float> test2=new OverClassApps3<Float>();
test1.setB(new Boolean(true));
test2.setB(new Float(12.3));
Boolean b=test1.getB();
Float f=test2.getB();
// Integer f=test2.getB(); // 此时编译器会报错
System.out.println(b);
System.out.println(f);
}
}