假设我们有
class Fruit implements Comparable<Fruit>
{
@Override
public int compareTo(Fruit o) { return 0; }
}
class Apple extends Fruit{}
class Main
{
public static void main (String args[])
{
function(new Apple()); // this shouldn't work because Apple is implementing Comparable<Fruit>, not Comparable<Apple>
}
public static<T extends Comparable<T>> void function(T t){}
} 代码工作正常,没有任何问题。
我的问题是为什么<T extends Comparable<T>>像<T extends Comparable<? super T>>一样工作。有什么区别吗?
谢谢。
编辑- 图像书中的一篇短文
发布于 2016-11-19 09:36:40
我认为您是用Java 8编译的。因为在Java 8之前,您不应该传递编译并有以下错误:
绑定不匹配: Main类型的泛型方法函数(T)不适用于参数(Apple)。推断类型Apple不能有效地替代有界参数>
我认为你在书中读到的是Java 8之前的通用用法。
但我不知道Java 8对这种情况的约束较少。
Java 8所称的“改进推理”是Java 8中大量使用推理的副作用吗?
发布于 2016-11-19 08:51:34
在本例中,它是因为Fruit类本身是一个超类。
区别就在这里
<T extends Comparable<T>>接受可与type T的论证相比较,<T extends Comparable<? super T>>接受可与type T and its super classes的论证相比较。在这里,因为在java中,每个类本身都是一个超类,所以Fruit is also a superclass of Fruit .Thats --为什么您看到它们的工作方式相同--但是如果您使用类Apple作为T,您就会看到区别。
https://stackoverflow.com/questions/40690788
复制相似问题