Downcasting in Java

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

    Using your example, you could do:

    public void doit(A a) {
        if(a instanceof B) {
            // needs to cast to B to access draw2 which isn't present in A
            // note that this is probably not a good OO-design, but that would
            // be out-of-scope for this discussion :)
            ((B)a).draw2();
        }
        a.draw();
    }
    

提交回复
热议问题