[英]How do I syntaxcially correctly implement an interface with type<K extends Comparable<K>, V>?
When you implement a generic interface, you should always specify the type arguments.当你实现一个泛型接口时,你应该总是指定类型参数。 You can get away with not specifying them, but then you are using raw types, which you shouldn't .您可以不指定它们,但是您使用的是原始类型, 而您不应该使用原始类型。
When you do specify them, you also need to specify them in a valid way.当你指定它们,你还需要一个有效的方式来指定。
First option is wrong because of two reasons:由于两个原因,第一个选项是错误的:
K extends Comparable<K>
is wrong当您指定类型参数时,您永远不会重写该参数的边界,因此编写K extends Comparable<K>
是错误的K
and V
are not defined anywhere. K
和V
没有在任何地方定义。 Second option is wrong because you rewrote the bounds on K
.第二个选项是错误的,因为您重写了K
的边界。 This option differs from the first option in that K
and V
are defined here - K
and V
are the type arguments of Son
.在第一选择此选项不同K
和V
在这里被定义- K
和V
是类型参数Son
。
Third option compiles, but it uses raw types, which kind of defeats the purpose of using generics in the first place.第三个选项编译,但它使用原始类型,这首先违背了使用泛型的目的。
Ideally, you would write something like:理想情况下,您会编写如下内容:
class Son<K extends Comparable<K>, V> implements Father<K, V> {
}
Note how I did not rewrite the bounds, and defined K
and V
as the type arguments for Son
.请注意我没有重写边界,并将K
和V
定义为Son
的类型参数。
Alternatively, specify a concrete type:或者,指定一个具体类型:
class Son implements Father<String, Integer> {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.