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. >
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.