[英]How come <T extends Comparable<T>> working as <T extends Comparable<? super T>>?
假设我们有
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>>
一样工作<T extends Comparable<? super T>>
<T extends Comparable<? super T>>
。 有什么不同 ?
谢谢。
[编辑]-图书图片的一段
在这种情况下,是因为类Fruit
是自身的超类
区别在这里
<T extends Comparable<T>>
接受Comparable与type T
争论<T extends Comparable<? super T>>
<T extends Comparable<? super T>>
接受<T extends Comparable<? super T>>
type T and its super classes
其父type T and its super classes
争论。 由于在Java中每个类都是其自身的超类,因此Fruit is also a superclass of Fruit
这就是为什么您看到它们以相同的方式工作的原因,但是如果您将Apple
类用作T
您会发现其中的区别。
我认为您可以使用Java 8进行编译。 因为在Java 8之前,您不应该通过编译并出现以下错误:
边界不匹配:Main类型的通用方法函数(T)不适用于自变量(Apple)。 推断的类型Apple不是边界参数的有效替代品>
我认为您在书中所读的内容是指Java 8之前的通用用法。
但是我不知道Java 8对这种情况的约束较少。
Java 8称为“改进的推理”是否是Java 8中大量使用推理的副作用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.