The Java™ Tutorials — Generics :Wildcards and Subtyping 泛型和子类

The Java™ Tutorials — Generics :Wildcards and Subtyping 泛型和子类

原文地址:https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html

关键点



全文翻译

As described in Generics, Inheritance, and Subtypes, generic classes or interfaces are not related merely because there is a relationship between their types. However, you can use wildcards to create a relationship between generic classes or interfaces.

正如在《泛型、继承和子类》中描述的那样,泛型类(接口)间并无关联。仅仅因为它们和它们的类型相关。然而,你可以通过使用通配符在泛型类(接口)间建立联系。

Given the following two regular (non-generic) classes:

下面给出两个常规的非泛型类:

class A { /* ... */ }
class B extends A { /* ... */ }

It would be reasonable to write the following code:

写下下面代码是十分合理的:

B b = new B();
A a = b;

This example shows that inheritance of regular classes follows this rule of subtyping: class B is a subtype of class A if B extends A. This rule does not apply to generic types:

下面范例表明了常规类的继承遵循了子类的这条规定:如果类B扩展自类A,那么B就是A的子类。这条规则对泛型并不适用:

List<B> lb = new ArrayList<>();
List<A> la = lb; // compile-time error

Given that Integer is a subtype of Number, what is the relationship between List<Integer> and List<Number>?

给定一个Integer,而它是Number的子类。那么List<Integer>List<Number>的关系是啥呢?

Although Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> and, in fact, these two types are not related. The common parent ofList<Number>and List<Integer> is List<?>.

虽然Integer为Number的子类,但是List<Integer>并非为List<Number>的子类,事实上,两者没关系。两者的共同父类为List<?>

In order to create a relationship between these classes so that the code can access Number’s methods through List<Integer>’s elements, use an upper bounded wildcard:

为了在这两个类中创建一个关系,从而让代码可以通过List<Integer>里面的元素调用Number里面的方法,你需要使用一个有上限通配符:

List<? extends Integer> intList = new ArrayList<>();
List<? extends Number> numList = intList; // OK. List<? extends Integer> is a subtype of List<? extends Number>

Because Integer is a subtype of Number, and numList is a list of Number objects, a relationship now exists between intList (a list of Integer objects) and numList. The following diagram shows the relationships between several List classes declared with both upper and lower bounded wildcards.

因为Integer是一个Number的子类型,并且numList是一个Number列表,现在intList(一个Integer列表)和numList间就存在了一种关系。下面的图表说明了几种通过有上下限通配符声明的几个List类间的关系。

The Guidelines for Wildcard Use section has more information about the ramifications of using upper and lower bounded wildcards.

更多关于有上(下)限通配符的衍生问题的信息,请参阅《通配符使用指南》


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值