引入
- 同一泛型类,如果实例化时给定的实际类型不同,则这些实例的类型是不兼容的,不能相互赋值
- 泛型类实例之间的不兼容性会带来使用的不便,我们可以使用 泛型通配符(?) 声明泛型类的变量。
class Animal{
}
class Dog extends Animal{
}
class Cls1<T>{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
}
public class Test {
public static void main(String[] args) {
Cls1<Integer> c1 = new Cls1<Integer>(10);
Cls1<Double> c2 = new Cls1<Double>(10.5);
Cls1<Object> c3 = new Cls1<Object>(10.5);
// c1 = c2; // 不行
// c1 = c3; // 不行
// c3 = c1; // 不行
}
}
通配符使用
应用场景:不知道返回来是一个什么类型,需要一个变量来接收返回
“?”代表任意一个类型
class Animal{
}
class Dog extends Animal{
}
class Cls1<T>{
T a;
public Cls1(T a){
this.a = a;
}
public T getData(){
return a;
}
}
public class Test {
public static void main(String[] args) {
Cls1<Integer> c1 = new Cls1<Integer>(10);
Cls1<Double> c2 = new Cls1<Double>(10.12);
Cls1<Dog> c3 = new Cls1<Dog>(new Dog());
Cls1<?> c4; //通配符
c4 = c3;
c4 = c2;
c4 = c1;
}
}
和限制泛型上下限相似,同样可以使用extends限定通配类型
Cls1<Integer> c1 = new Cls1<Integer>(10);
Cls1<Double> c2 = new Cls1<Double>(10.12);
Cls1<Dog> c3 = new Cls1<Dog>(new Dog());
Cls1<? extends Animal> c4; //通配符
c4 = c3; //只有这条可以
//c4 = c2;
//c4 = c1;
还可以使用super将通配符匹配类型限定为某个类型的下限
Cls1<Integer> c1 = new Cls1<Integer>(10);
Cls1<Double> c2 = new Cls1<Double>(10.12);
Cls1<Dog> c3 = new Cls1<Dog>(new Dog());
//Cls1<? extends Animal> c4; //通配符
Cls1<? super Dog> c4;
c4 = c3; //只有这条可以
//c4 = c2;
//c4 = c1;