The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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. 这个例子表明,常规类的继承遵循这个子类型化规则:如果B扩展了A,那么B类就是A类的子类型。This rule does not apply to generic types:此规则不适用于泛型类型:
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. 虽然Integer是Number的子类型,但是List<Integer>并不是List<Number>的子类型,而且,实际上这两种类型没有关系。The common parent of List<Number> and List<Integer> is List<?>.List<Number>和List<Integer>的共同父类是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. 因为Integer是Number的子类型,而numList是Number对象的列表,所以intList(一个Integer对象的列表)和numList之间现在有关系了。The following diagram shows the relationships between several List classes declared with both upper and lower bounded wildcards.下图显示了使用上下界通配符声明的几个List之间的关系。
The Guidelines for Wildcard Use section has more information about the ramifications of using upper and lower bounded wildcards.通配符使用指南部分提供了有关使用上限和下限通配符的影响的更多信息。