Once you create an object of a child class, you cannot convert it to a superclass. Just check out the examples below.
Assumptions: Dog is a child class that inherits from Animal (SuperClass)
Plain Typecast:
Dog dog = new Dog();
Animal animal = (Animal) dog;
Invalid Typecast:
Animal animal = new Animal();
Dog dog = (Dog) animal;
Below Typecast really works:
Dog dog = new Dog();
Animal animal = (Animal) dog;
dog = (Dog) animal; //This works
The compiler verifies its syntax for the actual runtime.
source
share