Friday 2 October 2015

instanceof Operator

The Type Comparison Operator instanceof

The instanceof operator compares an object to a specified type.

We generally use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

class Parent {

}

class Child extends Parent implements MyInterface {

}

interface MyInterface {

}

class InstanceofDemo {
      public static void main(String[] args) {
           Parent obj1 = new Parent();
           Parent obj2 = new Child();

           println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
           println("obj1 instanceof Child: " + (obj1 instanceof Child));
           println("obj1 instanceof MyInterface: "+
                                         (obj1 instanceof MyInterface));
           println("obj2 instanceof Parent: "+ (obj2 instanceof Parent));
           println("obj2 instanceof Child: "+ (obj2 instanceof Child));
           println("obj2 instanceof MyInterface: "+
                                        (obj2 instanceof MyInterface));
     }
     static void println(String string) {
           System.out.println(string);
     }
}

Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

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...