Why don't we get compile-time error for casting here?

shahidbits :

In the following example, why does the compiler not report an error for casting x to D?

interface X {}
class C implements X {}
class D {}

public class CastIssue {
    public static void main(String[] args) {
        X x = new C();

        // why is there no error here?
        D d = (D) x;
    }
}

But, if we make X a class, the compiler reports an error:

class X {}
class C extends X {}
class D {}

public class CastIssue {
    public static void main(String[] args) {
        X x = new C();

        // this gives a compile-time error
        D d = (D) x;
    }
}
kaya3 :

Casting from X to D is allowed because it's possible for an object to be an instance of both X and D. For example:

class E extends D implements X {}
X x = new E();
D d = (D) x; // no problem here, because an X can be a D too

In your example, we can determine from the sequence of statements that the cast will fail, but Java cannot, because it does not consider the flow of control when determining types at compile-time.

However, if X is a class, then because X and D would have no common subclasses (Java does not allow multiple inheritance for classes), it would be impossible for an object to be an instance of both unrelated classes. In that case, the cast is not allowed because based on the compile-time types, the cast could never succeed (unless x is null).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=218389&siteId=1