In java:
Base b = new Base();
Derived d = (Derived)b;
throws ClassCastException
. Why? Why downcasting throws Exception<
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.