日期:2014-05-20  浏览次数:20689 次

问一个java语言规范纯理论问题
A variable of an interface type can hold a null reference or a reference to any
instance of any class that implements the interface.
Note that a variable is not guaranteed to always refer to a subtype of its declared type, but
only to subclasses or subinterfaces of the declared type. This is due to the possibility of
heap pollution discussed below.

------The Java? Language Specification Java SE 7 Edition 第4章 4.12.2

请问上面讲到的subtype 跟subclass,subinterface分别指的是什么?

------解决方案--------------------
补充一下,好型泛型不属于这个行列,出现泛型的地方,我认为可以都把它替换成Object,Java的泛型采用的是类型擦除,比如:类定义class A<T>{},定义变量 A<Integer> a;应该等同于Object a;泛型的继承也不是简单的类继承,比如:A<Number> a1; A<Integer> a2=new A<>();(new A<>()属于Java7的菱形推断,Java7之前用new A<Integer>()),a1=a2;(这条语句是错误的,可以理解为A<Integer>并不继承自A<Number>,虽然Integer继承Number,具体的翻译一下,Object a1;Object a2=new Object();说明a2具有的类型并不是继承自a1所具有的类型。这里看似好想a1=a2可以是对的,但是Java泛型的设计者为了安全考虑,也屏蔽了底层的Java虚拟机,所以a1=a2在Java编译器编译时是通不过的。)。最后,Java的泛型的继承,以及使用,如果完全理解其原理,一句两句也说不清楚,涉及Java虚拟机,Java编译器,Java语言语法等之间的关系理解。好像听说Java的后续版本会在虚拟机层面支持泛型,具体的理解,正确与否,参见Oracle的官方文档资料。