简体   繁体   English

具有接口的古怪行为

[英]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来实现Facepublic 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)

  1. Can't speak for the designers of Java generics, but presumably they did this to simplify the language. 不能代表Java泛型的设计者,但大概是他们这样做是为了简化语言。 The point of an 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是一个接口或类,所以让你使用implementsextends基于是否Y是一个或其他似乎很麻烦。
  2. Try: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM