Wednesday 4 November 2015

Downcasting with java instanceof operator

When Subclass type refers to the object of Parent class, it is known as downcasting.

If we perform it directly, compiler gives Compilation error.

If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, down casting is possible.

class Parent1 {

}
class Child1 extends Parent1 {
      static void method(Parent1 obj) { 
           if(obj instanceof Child1){ 
                  Child1 obj1 = (Child1)obj//downcasting 
                  System.out.println("downcasting successfully !!"); 
           } 
      }
}

class DownCasting {
      public static void main(String[] args) {
            Parent1 obj=new Child1();
           Child1.method(obj);
     }
}

Output:
downcasting successfully !! 


If we apply the instanceof operator with any variable that has null value, it returns false.

Prefer polymorphism over instanceof and downcasting.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...