Why Downcasting throws Exception?

前端 未结 4 1033
囚心锁ツ
囚心锁ツ 2021-01-19 05:18

In java:

Base b = new Base();
Derived d = (Derived)b; 

throws ClassCastException. Why? Why downcasting throws Exception<

4条回答
  •  再見小時候
    2021-01-19 05:30

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

    if (animal instanceof Cat) {
      Cat cat = (Cat) animal;
    }
    

    Here, Animal is the parent class and Cat 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.

提交回复
热议问题