package Thread1;
class Info{
private T var ; // 定义泛型变量publicvoid setVar(T var){
this.var = var ;
}
public T getVar(){
returnthis.var ;
}
public String toString(){ // 直接打印returnthis.var.toString() ;
}
};
publicclass demo1{
publicstaticvoid main(String args[]){
Info<?> i = new Info() ; // 使用String为泛型类型
i.setVar("MLDN") ; // 设置内容,这里会出错,因为”?“通配符修饰的对象只能接收,不能修改,也就是不能设置。 }
};
运行结果:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method setVar(capture#1-of ?) in the type Info is not applicable for the arguments (String)
at Thread1.demo1.main(demo1.java:17)
class Info{
private T var ; // 定义泛型变量publicvoid setVar(T var){
this.var = var ;
}
public T getVar(){
returnthis.var ;
}
public String toString(){ // 直接打印returnthis.var.toString() ;
}
};
publicclass GenericsDemo21{
publicstaticvoid main(String args[]){
Info i1 = new Info() ; // 声明String的泛型对象
Info
class Info{
private T var ; // 定义泛型变量publicvoid setVar(T var){
this.var = var ;
}
public T getVar(){
returnthis.var ;
}
public String toString(){ // 直接打印returnthis.var.toString() ;
}
};
publicclass GenericsDemo23{
publicstaticvoid main(String args[]){
Info i1 = new Info() ; // 泛型类型为String
Info i2 = null ;
i2 = i1 ; //这里因为对象泛型类型不同,而出错。 }
};
代码示例:
import java.util.ArrayList;
import java.util.List;
class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}
publicclass CovariantArrays {
publicstaticvoid main(String[] args) {
//上界
List<? extends Fruit> flistTop = new ArrayList();
flistTop.add(null);
//add Fruit对象会报错
//flist.add(new Fruit());
Fruit fruit1 = flistTop.get(0);
//下界
List<? super Apple> flistBottem = new ArrayList();
flistBottem.add(new Apple());
flistBottem.add(new Jonathan());
//get Apple对象会报错
//Apple apple = flistBottem.get(0); }
}