Given:
2. public class Organic<E> {
3. void react(E e) { }
4. static void main(String[] args) {
5. // Organic<? extends Organic> compound = new Aliphatic<Organic>();
6. // Organic<? super Aliphatic> compound = new Aliphatic<Organic>();
7. compound.react(new Organic());
8. compound.react(new Aliphatic());
9. compound.react(new Hexane());
10. } }
11. class Aliphatic<F> extends Organic<F> { }
12. class Hexane<G> extends Aliphatic<G> { }
Which, taken independently, are true? (Choose all that apply.)
A. If line 5 is uncommented, compilation fails due to an error at line 7.
B. If line 5 is uncommented, compilation fails due to an error at line 8.
C. If line 5 is uncommented, compilation fails due to an error at line 9.
D. If line 6 is uncommented, compilation fails due to an error at line 7.
E. If line 6 is uncommented, compilation fails due to an error at line 8.
F. If line 6 is uncommented, compilation fails due to an error at line 9.
答案是ABCD,求解释! 多谢
extends关键字声明了类型的上界,表示参数化的类型可能是所指定的类型,或者是此类型的子类
super关键字声明了类型的下界,表示参数化的类型可能是所指定的类型,或者是此类型的父类型,直至Object
? extends Organic 表示任何Organic或Organic的子类 即可以是Organic的子类
? super Aliphatic 表示任何Aliphatic或Aliphatic的父类 即可以是Aliphatic、Organic、Object
再使用? extends T 和 ? super T 时 有一个限制:
Organic<------Aliphatic<------Hexane
1、Organic<? extends Organic> compound = new Aliphatic();
先拿Number<-------Integer/Long/Double来举例:
List intList = new ArrayList();
List<? extends Number> numList = intList;
如果
numList.add(Integer);/numList.add(Long);/numList.add(Double);
则通过intList取到的数据可能就是错误的,因此 ? extends T 只能表示获取数据 不能修改数据,可以这么用:
[code="java"] class Organic {
E e;
void react(E e) { }
E get() {
return e;
}
}[/code]
compound.get();
2、Organic<? super Aliphatic> compound = new Aliphatic();
先举例:
List aList = new ArrayList();
List<? super Aliphatic> bList = aList;
bList.add(new Organic());
bList.add(new Aliphatic());
bList.add(new Hexane());
? super Aliphatic ----->Aliphatic Hexane都是合法的;可以添加到bList集合,也可以添加到aList集合。
但是获取必须,因为? super Aliphatic 可以追溯到Object
Aliphatic a = bList.get(1); //错误
Object a = bList.get(1); //正确
总结:
? extends T 上界
约束[color=red]获取时[/color]类型为上界为T(即返回值可以是T/T的父类),不能设置值
? super T 下界
约束[color=red]设置时[/color]类型下界为T(即参数可以是T/T的子类),获取值必须Object(即无泛型 返回值必须Object)。