在Java中泛型的扩展 [英] implements vs extends in generics in Java
问题描述
MaxPQ代表优先级队列,它是可以相互比较的Key对象的集合。代码1:
public class MaxPQ< Key extends Comparable< / p>密码>>> {
...
}
/ p>
public class MaxPQ< Key implements Comparable< Key>> {
...
}
第二个代码不能编译,但它不直观,为什么我们需要扩展而不是实现使用通用的接口。
区别非常简单:第二个代码片段不会编译,永远不会。对于泛型,您总是对类和接口都使用 extends
。此外,还可以使用 super
关键字,但它具有不同的语义。
Can someone tell me what the differences between the first and second codes are? MaxPQ stands for priority queue, which is a collection of "Key" objects that can be compared with each other.
Code 1:
public class MaxPQ<Key extends Comparable<Key>>{
...
}
Code 2:
public class MaxPQ<Key implements Comparable<Key>>{
...
}
The second code doesn't compile, but it is not intuitive to me why we need to extend instead of implement interfaces when using a generic.
The difference is pretty straightforward: second code snippet does not compile and never will. With generics you always use extends
, for both classes and interfaces. Also super
keyword can be used there, but it has different semantics.
这篇关于在Java中泛型的扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!