Object of the Classes which are at the same level in the hierarchy cannot be casted with each other. Lets understand this with the below example -
Lets assume -
- Animal is the Super Class of Dog and Cat Classes
- Dog and Cat Classes are at the same level in the hierarchy as shown below
From the above screenshot, casting the objects of the Class at the same level i.e. Dog and Cat is not possible as Dog cant be a Cat and also Cat cant be a Dog.
But lets implement this Hierarchy on Eclipse IDE and find out what happens when we try to cast the objects of the Classes which are at the same level in the hierarchy by following the below steps -
1. Launch Eclipse IDE and create a new Java Project 'Project 36' as shown below -
2. Create a Java Class 'ClassOne' with main( ) method as shown below -
3. Create two classes Dog Class and Cat Class in ClassOne class at same level in Hierarchy as shown below -
4. Create object for Cat Class as shown below -
5. Define object for Dog class and assign the object of Cat Class to the defined Dog Class reference variable as shown below -
6. View the compiler error as shown below -
The above error message says, it cannot convert the Cat Class type object to Dog Class type object while assigning the Cat Class object to Dog Class object.
Hence the objects of Classes which are at the same level in the hierarchy cannot be casted with each other.
Please comment below to feedback or ask questions.