Downcasting in Java

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

    I believe this applies to all statically typed languages:

    String s = "some string";
    Object o = s; // ok
    String x = o; // gives compile-time error, o is not neccessarily a string
    String x = (String)o; // ok compile-time, but might give a runtime exception if o is not infact a String
    

    The typecast effectively says: assume this is a reference to the cast class and use it as such. Now, lets say o is really an Integer, assuming this is a String makes no sense and will give unexpected results, thus there needs to be a runtime check and an exception to notify the runtime environment that something is wrong.

    In practical use, you can write code working on a more general class, but cast it to a subclass if you know what subclass it is and need to treat it as such. A typical example is overriding Object.equals(). Assume we have a class for Car:

    @Override
    boolean equals(Object o) {
        if(!(o instanceof Car)) return false;
        Car other = (Car)o;
        // compare this to other and return
    }
    

提交回复
热议问题