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>
andList<Number>
?
给定一个Integer,而它是Number的子类。那么List<Integer>
和List<Number>
的关系是啥呢?
Although Integer is a subtype of Number,
List<Integer>
is not a subtype ofList<Number>
and, in fact, these two types are not related. The common parent ofList<Number>
andList<Integer>
isList<?>
.
虽然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.
更多关于有上(下)限通配符的衍生问题的信息,请参阅《通配符使用指南》