实现vs在Java中的泛型中扩展

时间:2021-12-05 15:20:24

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.

有人能告诉我第一个和第二个代码之间的区别是什么吗? MaxPQ代表优先级队列,它是可以相互比较的“密钥”对象的集合。

Code 1:

代码1:

public class MaxPQ<Key extends Comparable<Key>>{
...
}

Code 2:

代码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.

第二个代码没有编译,但是对于我来说,为什么在使用泛型时我们需要扩展而不是实现接口是不直观的。

3 个解决方案

#1


11  

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


1  

There is no implements in generics. The second code is invalid. You probably confusing with :

泛型中没有工具。第二个代码无效。你可能会混淆:

public class MaxPQ implements Comparable<Key> {
   ...
}

#3


0  

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"?

当然,扩展的含义与类定义中的典型用法完全不同。 Angelika Langer在Java中有关于扩展的不同含义的好文本:“扩展”总是意味着“继承”吗?

#1


11  

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


1  

There is no implements in generics. The second code is invalid. You probably confusing with :

泛型中没有工具。第二个代码无效。你可能会混淆:

public class MaxPQ implements Comparable<Key> {
   ...
}

#3


0  

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"?

当然,扩展的含义与类定义中的典型用法完全不同。 Angelika Langer在Java中有关于扩展的不同含义的好文本:“扩展”总是意味着“继承”吗?