【The Java™ Tutorials】【Generics】5. Generics, Inheritance, and Subtypes

我们先来看一段代码:

String s = new String();
Object o = s;

这样写是没有问题的,因为String是Object的子类。现在我们来看另一段代码:

List ls = new ArrayList();
List lo = ls;  //compile error
 
 

这段代码能过通过编译吗?答案是不行,因为虽然String是Object的子类,但是List不是List的子类。List和List都是Object的子类。

【The Java™ Tutorials】【Generics】5. Generics, Inheritance, and Subtypes_第1张图片
Box is not a subtype of Box even though Integer is a subtype of Number.

Generic Classes and Subtyping

【The Java™ Tutorials】【Generics】5. Generics, Inheritance, and Subtypes_第2张图片
A sample Collections hierarchy

假设我们自己定义了一个接口,他继承了List这个接口:

interface PayloadList extends List {
  void setPayload(int index, P val);
  ...
}

那么就会有以下层级关系:


【The Java™ Tutorials】【Generics】5. Generics, Inheritance, and Subtypes_第3张图片
A sample PayloadList hierarchy

你可能感兴趣的:(【The Java™ Tutorials】【Generics】5. Generics, Inheritance, and Subtypes)