Java泛型 - 实现和扩展

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3985225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:55:49  来源:igfitidea点击:

Java Generics - implements and extends

javagenerics

提问by Shweta

I am trying to write something like

我正在尝试写一些类似的东西

public class A implements B<T implements C> {}

and

public abstract class M<I extends P> extends R<I extends P> implements Q<I extends P> {}

but I am getting errors like Multiple markers and syntax error on token extends, expected. Please let me know what is the correct way of doing this.

但是我在令牌扩展上遇到了诸如多个标记和语法错误之类的错误,预期。请让我知道这样做的正确方法是什么。

回答by Bozho

There is no implementskeyword in generic bounds. It's only extends

implements泛型边界中没有关键字。这只是extends

Furthermore - you should specify the type parameter only in the class definition, and not in supertypes. I.e.

此外 - 您应该只在类定义中指定类型参数,而不是在超类型中。IE

public class A<T extends C> implements B<T> {}

回答by Colin Hebert

When you have interfaces in generics, you still have to use the extendskeyword.

当您在泛型中有接口时,您仍然必须使用extends关键字。

In your case, if you know what Twill be :

在您的情况下,如果您知道T将是什么:

public class A<T extends C> implements B<T> {}

If you don't and you simply have to implements Bwith a Ctype :

如果你不这样做,你只需要实现B一个C类型:

public class A implements B<C> {}

For the second part, once you've defined Iyou can use it as is in your other generic types :

对于第二部分,一旦定义,I您就可以在其他泛型类型中使用它:

public abstract class M<I extends P> extends R<I> implements Q<I> {}


Resources :

资源 :