1.上限与下限
1.上限extends
格式:<? extends Person>。Person表示一个类
1.上限表示只能传入这个类的子类,子子类……,这个类
下面的方法中,只能传入子类或者自己:
show(new Test());
show(new Test());
show(new Test());
,如果传入父类:
show(new Test());这个也不行
show(new Test());//由于上限是Person,所以这里会报错
就会报错
/**
* extends表示上限,这里表示只能是Person的子类,或者person
* @param test 传入上限为person的子类,最高为person
* @param <T>
*/
public static <T> void show(Test<? extends Person> test){
}
2.下限super
1.下限表示只能传入这个类的父类,父父类……,这个类
下面的方法中,只能传入父类获者自己:show1(new Test());
show1(new Test());
如果传入其他的:传子类:
show1(new Test());//这里会报错,因为Worker是person的子类
就会报错
/**
* super表示下限,这里表示只能是Person的父类,或者person
* @param test 传入上限为person的子类,最高为person
* @param <T>
*/
public static <T> void show1(Test<? super Person> test){
}
2.读写模式:
1.可读不可写
//可读不可写
Test<? extends Person> test=null;
// test.add(new Person());//报错
// test.add(new Student());//报错
// test.add(new Object());//报错
// test.add(new Worker());//报错
Person t = test.getT();//返回的直接是一个Person,所以可以读
2.可写不完全可读(要强制转换)
//可写不完全可读
Test<? super Person> test1=null;
test1.add(new Person());//可写
test1.add(new Student());//可写
test1.add(new Worker());//可写
// test1.add(new Animal());//不可以,因为Animal是父类,只能子类或者自己
Object t1 = test1.getT();//返回的是一个object,我们要强制转换,所以不完全可读