Java 规范中难以理解的条件

Difficult condition to understand on Java Specification

在阅读 Java 的 SE 规范中的引用类型转换时:

Given a compile-time reference type S (source) and a compile-time reference type T (target), a casting conversion exists from S to T if no compile-time errors occur due to the following rules.

我不断发现以下情况:

If S is a class type: If T is a class type, then either |S| <: |T|, or |T| <: |S|. Otherwise, a compile-time error occurs.

Furthermore, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types (§4.5), and that the erasures of X and Y are the same, a compile-time error occurs.

任何人都可以给我一个这种情况的例子吗?

编辑:

有关我引用的文章的进一步说明,请参阅关于此 link

的第 5.5.1 节

条件的第一部分要求S <: TS :> T,即一个class必须继承另一个;否则会出现编译时错误。所以您的基本设置如下所示:

class T {
}
class S extends T {
}

到目前为止一切顺利:您可以将 S 转换为 T,因为两个 class 之间存在适当的子class 关系。

现在让我们看一下条件的第二部分:两个 classes 必须有不同的超类型。由于只允许有一个 superclass,公共超类型需要是一个接口。下面是如何打破规则第二部分的一个例子:

// X is List<String>
class T implements List<String> {
}
// Y is List<Integer>
class S extends T implements List<Integer> {
}

XY 的擦除需要实现 List<???>,但列表必须在不同的类型上进行参数化。这会导致编译时错误,因为 S 无法同时满足 List<String>List<Integer> 接口。