开发者

Why is implementing a generic interface so counter intuitive?

开发者 https://www.devze.com 2023-01-20 00:41 出处:网络
interface Foo<T开发者_运维百科 extends Number>{ } class Bar<T extends Number> implements Foo<T>{
interface Foo<T开发者_运维百科 extends Number>{
}

class Bar<T extends Number> implements Foo<T>{

}

Why does the class have to be written that way instead of:

class Bar<T extends Number> implements Foo<T extends Number>{
}

Surely the second way is clearer.


Because that's the same T, so it's redundant to say it extends Number again.


In the line

class Bar<T extends Number> implements Foo<T> {

T is defined at the first occurrence and used at the second. extends Number constrains the type that T can be instantiated with. You can put such constraints only at the place where T is defined.

It is similar to ordinary function parameters, where you write the type only in the declaration and not at the places where you use the parameter.

0

精彩评论

暂无评论...
验证码 换一张
取 消