泛型扩展和实现 [英] Generic extends and implements

查看:83
本文介绍了泛型扩展和实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆