Google+

208. You cannot cast objects of Classes which are at the same level in hierarchy








Pre-requisite -



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.

Downcasting will be explained in the next post.





1 comment:

Unknown said...

@Arun - Dog and Cat classes are not subclasses of ClassOne class here. Shouldn't these be subclasses of ClassOne?

I guess if these are not the sub-classes, then also these are in the same level of hierarchy and concept wise it is correct but concept is explained using subclasses and implemented without using subclasses. This may confuse users.