implements vs extends in generics in Java

一世执手 提交于 2019-11-29 07:26:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!