Difficult condition to understand on Java Specification

while reading on reference type casting in Java's SE specification:

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.

I keep finding the following kind of condition:

If S is a class type: If T is a class type, then either |S| <: |T| |S| <: |T| , or |T| <: |S| |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.

Can anybody give me an example of this situation?

EDIT:

For further clarification of the article I'm citing refer to section 5.5.1 on this link


The first part of the condition requires that either S <: T or S :> T , ie one class must inherit from the other; otherwise there would be a compile-time error. So your basic setup looks like this:

class T {
}
class S extends T {
}

So far so good: you are allowed to cast S to T , because there is a proper subclass relationship between the two classes.

Now let's look at the second part of the condition: the two classes must have different supertypes. Since only one superclass is allowed, the common supertype needs to be an interface. Here is one example of how to break the second part of the rule:

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

Erasures of both X and Y need to implement List<???> , but the list must be parameterized on a different type. This causes a compile-time error, because S has no way of satisfying both List<String> and List<Integer> interfaces.

链接地址: http://www.djcxy.com/p/28862.html

上一篇: 将詹金斯的工作输出传递给另一份工作

下一篇: 关于Java规范的理解困难