chensifeng 2012-09-09 16:32
浏览 270
已采纳

Java范型一问

 

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,求解释! 多谢

  • 写回答

1条回答 默认 最新

  • jinnianshilongnian 2012-09-09 17:47
    关注

    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)。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序