简体   繁体   English

为什么我们在此处进行转换不会出现编译时错误?

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

In the following example, why does the compiler not report an error for casting x to D ?在下面的例子中,为什么编译器不报告将xD的错误?

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:但是,如果我们让X成为一个类,编译器会报错:

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;
    }
}

Casting from X to D is allowed because it's possible for an object to be an instance of both X and D .允许从X强制转换为D ,因为对象可能是XD的实例。 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.在您的示例中,我们可以从语句序列中确定强制转换失败,但 Java 不能,因为它在编译时确定类型时不考虑控制流。

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.然而,如果X是一个类,那么因为XD没有共同的子类(Java 不允许类的多重继承),一个对象不可能是两个不相关类的实例。 In that case, the cast is not allowed because based on the compile-time types, the cast could never succeed (unless x is null ).在这种情况下,不允许强制转换,因为基于编译时类型,强制转换永远不会成功(除非xnull )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM