问题
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.
回答1:
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.
回答2:
There is no implements in generics. The second code is invalid. You probably confusing with :
public class MaxPQ implements Comparable<Key> {
...
}
回答3:
I assume it was decided to use extends
for both interfaces and classes, because in the case of generic class declaration it does not make any difference is type argument bound to interface or to class.
Of course meaning of extends
is quite different from its typical usage in class definition. Angelika Langer do have nice text about different meanings of extends
in Java: Does "extends" always mean "inheritance"?
来源:https://stackoverflow.com/questions/10971888/implements-vs-extends-in-generics-in-java