[英]Weird Generics Behaviour with Interface
I want to create a generic class that takes elements of some generic type that are comparable. 我想创建一个通用类,该通用类采用可比较的某些通用类型的元素。 So I do:
所以我做:
public class Foo<T extends Comparable<T>>
and inside the class Foo
I have things like: 在
Foo
类中,我有类似以下内容:
public void bar(T t)
and I'm assured that I can write code like this: t.compareTo(v)
. 并且我确信我可以编写如下代码:
t.compareTo(v)
。
Question 1: Why when using generics we have extends
instead of implements
for an interface? 问题1:为什么在使用泛型时我们
extends
而不是接口的implements
? Comparable
is not a class. Comparable
不是一个类。
\\\\ \\\\
Assume now that I want to create another similar class to the above also implementing the bar
method. 现在假设我想创建另一个与上述类似的类,同时实现
bar
方法。 I thought of creating this interface: 我想到创建此接口:
public interface Face<T extends Comparable<T>> {
public void bar(T t);
}
and then I change class Foo
to implement Face
( public class Foo<T extends Comparable<T>> implements Face
). 然后我更改类
Foo
来实现Face
( public class Foo<T extends Comparable<T>> implements Face
)。
Question 2: When doing this I get the following compile error: 问题2:执行此操作时,出现以下编译错误:
The method bar(T) of type Foo must override or implement a supertype method . 类型为Foo的方法bar(T)必须重写或实现一个超类型方法 。
Why is this? 为什么是这样?
When I tell Eclipse to add the unimplemented methods
I get: public void bar(Comparable t)
instead of ... bar(T t)
. 当我告诉Eclipse
add the unimplemented methods
我得到: public void bar(Comparable t)
而不是... bar(T t)
。
X extends Y
constraint is that we want to specify that X
is assignable to type Y
- in the end it's immaterial whether Y
is an interface or a class, so making you use implements
or extends
based on whether Y
is the one or the other seems like a hassle. X extends Y
的约束是,我们要指定X
是分配给输入Y
-在它的非物质是否结束Y
是一个接口或类,所以让你使用implements
或extends
基于是否Y
是一个或其他似乎很麻烦。 public class Foo<T extends Comparable<T>> implements Face<T>
- Face is an interface with a type parameter, so you need to fill in that type parameter when extending the interface. public class Foo<T extends Comparable<T>> implements Face<T>
-Face是带有类型参数的接口,因此在扩展接口时需要填写该类型参数。 Please re-format your question a bit. 请重新格式化您的问题。 But if I understood anything there, do this:
但是,如果我在那里了解任何内容,请执行以下操作:
// Face<T>, not just Face
public class Foo<T extends Comparable<T>> implements Face<T> {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.