Downcasting in Java

后端 未结 11 2373
自闭症患者
自闭症患者 2020-11-22 03:15

Upcasting is allowed in Java, however downcasting gives a compile error.

The compile error can be removed by adding a cast but would anyway break at the runtime.

11条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 03:22

    We can all see that the code you provided won't work at run time. That's because we know that the expression new A() can never be an object of type B.

    But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:

    variable_of_type_B = (B)expression_of_type_A;
    

    And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type B. The compiler sees that A and B have a subtype relation, so with the "expression" view of the code, the cast might work.

    The compiler does not consider the special case when it knows exactly what object type expression_of_type_A will really have. It just sees the static type as A and considers the dynamic type could be A or any descendant of A, including B.

提交回复
热议问题