Types of Casting & instanceof

upcasting-downcasting

You must understand, that by casting you are not actually changing the object itself, you are just labeling it differently.

upcasting

  • Object of child class is assigned to reference varibale of parent type.
  • You do not need to upcast manually (implicit).
Manager x = new Manager();
Employee e = x;            // Doesn't need (Employee) before the x. 

downcasting

  • Object of parent class is assigned to reference varibale of child type.
  • You need to downcast manually which subtype to downcast (Explicit). Unless, compiler doesn’t know which subtype to downcast.
    • ex) Employee can downcast to either Manager or Clerk
Employee e = new Manager();
Manager x = (Manager) e;                // (Manager) is needed

 

  • If subtype is different, you will get ClassCastException.
  • To avoid the exception, you need to check which original subtype it was.
Employee e = new Clerk();
Manager x = (Manager) e;       // ClassCastException. 
                               // Original subtype is Clerk()

instanceof

  • You can use instanceof if casting is possible.
class Animal{}
class Dog extends Animal{
   static void cast(Animal a){
      Dog d = (Dog) a;              // Downcasting
   }

   public static void main(String[] args){
      Animal a1 = new Dog();
      if(a1 instanceof Dog){        // True
         Dog.cast(a1);              
      }
      
      Animal a2 = new Animal();
      if(a2 instanceof Dog){        // False
         Dog.cast(a2);              
      }
   }   
}

 

 

 

Leave A Comment

Your email address will not be published. Required fields are marked *