Downcasting in Java

后端 未结 11 2400
自闭症患者
自闭症患者 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:35

    Downcasting is allowed when there is a possibility that it succeeds at run time:

    Object o = getSomeObject(),
    String s = (String) o; // this is allowed because o could reference a String
    

    In some cases this will not succeed:

    Object o = new Object();
    String s = (String) o; // this will fail at runtime, because o doesn't reference a String
    

    When a cast (such as this last one) fails at runtime a ClassCastException will be thrown.

    In other cases it will work:

    Object o = "a String";
    String s = (String) o; // this will work, since o references a String
    

    Note that some casts will be disallowed at compile time, because they will never succeed at all:

    Integer i = getSomeInteger();
    String s = (String) i; // the compiler will not allow this, since i can never reference a String.
    

提交回复
热议问题