Downcasting in Java

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

    To do downcasting in Java, and avoid run-time exceptions, take a reference of the following code:

    if (animal instanceof Dog) {
      Dog dogObject = (Dog) animal;
    }
    

    Here, Animal is the parent class and Dog is the child class.
    instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.

提交回复
热议问题