Java generics - why is “extends T” allowed but not

2019-01-02 19:41发布

I wonder if there is a special reason in Java for using always "extends" rather than "implements" for defining bounds of typeparameters.

Example:

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

is prohibited but

public class A<B extends C>{} 

is correct. What is the reason for that?

标签: java generics
8条回答
倾城一夜雪
2楼-- · 2019-01-02 20:05

There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).

查看更多
与风俱净
3楼-- · 2019-01-02 20:07

The answer is in here :

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound […]. Note that, in this context, extends is used in a general sense to mean either extends (as in classes) or implements (as in interfaces).

So there you have it, it's a bit confusing, and Oracle knows it.

查看更多
弹指情弦暗扣
4楼-- · 2019-01-02 20:08

It's sort of arbitrary which of the terms to use. It could have been either way. Perhaps the language designers thought of "extends" as the most fundamental term, and "implements" as the special case for interfaces.

But I think implements would make slightly more sense. I think that communicates more that the parameter types don't have to be in an inheritance relationship, they can be in any kind of subtype relationship.

The Java Glossary expresses a similar view.

查看更多
高级女魔头
5楼-- · 2019-01-02 20:09

Because interfaces are just classes, except they don't have attributes or implementations. The only use of the keyword "implements" is to allow a class to inherit multiple interfaces, but not multiple classes, and we can see it in the code. I don't know if they will specify this in the future, but this is not a must.

查看更多
冷夜・残月
6楼-- · 2019-01-02 20:12

The "extends" in this context, means just like implements in interfaces and extends in classes. Here is more explanation

查看更多
梦寄多情
7楼-- · 2019-01-02 20:15

It may be that the base type is a generic parameter, so the actual type may be an interface of a class. Consider:

class MyGen<T, U extends T> {

Also from client code perspective interfaces are almost indistinguishable from classes, whereas for subtype it is important.

查看更多
登录 后发表回答