Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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|, 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.

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

like image 733
Rodrigo Avatar asked Sep 03 '15 18:09

Rodrigo


1 Answers

The first part of the condition requires that either S <: T or S :> T, i.e. 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.

like image 84
Sergey Kalinichenko Avatar answered Sep 27 '22 17:09

Sergey Kalinichenko