Java instanceof and its applications

Java Programming Java 8Object Oriented Programming

instanceof operator is used to check the type of object passed. Following rules explain the usage of instanceof operator in Java.

  • instanceof operator returns true for the object if checked against its class type.

  • instanceof operator returns false for the object if checked against its type which is not in its hierarchy.

  • instanceof operator returns true for the child object if checked against parent object type.

  • instanceof operator returns true for the complete object hierarchy up to the Object class.

  • instanceof operator returns false for the null value.

  • instanceof operator returns false for the parent object if checked against child object type.

Following example showcases the above concepts.

Example

 Live Demo

class SuperClass {
   int value = 10;
}

class SubClass extends SuperClass {
   int value = 12;
}

public class Tester{
   public static void main(String[] args){
      SuperClass obj = new SubClass();

      //instanceof returns true for the complete Object Hierarchy
      if(obj instanceof SubClass){
         System.out.println("obj is instanceof SubClass");
      }
      if(obj instanceof SuperClass){
         System.out.println("obj is instanceof SuperClass");
      }
      if(obj instanceof Object){
         System.out.println("obj is instanceof Object");
      }

      SuperClass obj1 = null;

      //instanceof returns false for null
      if(obj1 instanceof SuperClass){
         System.out.println("null is instanceof SuperClass");
      }

      SuperClass obj2 = new SuperClass();

      //instanceof returns false for the subclass
      if(obj2 instanceof SubClass){
         System.out.println("obj2 is instanceof SubClass");
      }
      if(obj2 instanceof SuperClass){
         System.out.println("obj2 is instanceof SuperClass");
      }
   }
}

Output

obj is instanceof SubClass
obj is instanceof SuperClass
obj is instanceof Object
obj2 is instanceof SuperClass
raja
Published on 19-Sep-2018 14:07:19
Advertisements