泛型扩展和实现 [英] Generic extends and implements
问题描述
我不明白为什么Company
编译.我以为它检查了extends
,但没有检查implements
?
I don't understand why Company
compiled. I thought it checked for extends
but not for implements
?
public interface Employee
public class HourlyEmployee implements Employee
public class Company<T extends Employee>
Company<HourlyEmployee> company = new Company<>();
推荐答案
泛型中的extends
关键字的语义与常规extends
关键字略有不同.
The extends
keyword in Generics has a slightly different semantics than the general extends
keyword.
在泛型的上下文中使用extends
时,例如T extends Something
,这意味着T
应该是 实现接口Something
的类型(在Something
是接口),或是Something
的子类(如果Something
是类).
When using extends
in the context of Generics, for example T extends Something
, this means that T
should be a type that either implements the interface Something
(in cases when Something
is interface), or is a subclass of Something
(in case Something
is a class).
可能的原因是,如果泛型中支持implements
关键字,这会使类型参数声明变得过于冗长.
Probably the reason for this is that if the implements
keyword was supported in Generics, this would have made type-parameter declaration too verbose.
例如,您将拥有:
<T extends SomeClass implements Serializable & Observable>
相反,此方法的有效语法为:
Instead, the valid syntax for this would be:
<T extends SomeClass & Serializable & Observable>
实际上,您不需要implements
关键字.在定义类型T
的边界时,只需指出类型T
源自哪个 types 即可,而不必关心它们是接口还是类.
And you don't need to have the implements
keyword, actually. When defining the bounds of a type T
, you just need to point out which types does your type T
derive from, without caring if those are interfaces or classes.
类型定义不是类定义.您可以将类型定义视为联接了几个数据集,其中结果集就是您的类型T
.
The type definition is not a class definition. You can consider type definition as joining few data sets, where the resulting set is your type T
.
这篇关于泛型扩展和实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!