by Dinesh Thakur

Sometimes it is useful to know the type of the object at runtime. For example, if you try to make a cast that is invalid, an exception will be thrown. You can overcome this problem if you are able to verify that the object is of the type you expect before you make the cast. This is possible using the instanceof operator. The general from of instanceof operator is objRef instanceof type

Here, objRef is a reference to an instance of a class and type is a class type. The instanceof operator returns true if the objRef is of the same type as the right operand or can be cast into any of the subclass type, otherwise it returns false.

Consider the same Shape hierarchy as discussed in previous section and we want to check whether reference variable s contains an object of type Rectangle then it will be written as

if(s instanceof Rectangle)

System.out.println ("Contains reference to Rectangle object");

else

System.out.println ("Contains reference to other object");

class Shape

{  
       public void area ()
       { 
         System.out.println("Base class area method is called");
       }
}
      class Rectangle extends Shape
  {
       private double length,breadth;
       Rectangle(double x,double y)
       {
         length = x ;
         breadth = y ;    
       }
       public void area()
       {
          System.out.println("Area of Rectangle is = " + (length  * breadth));
       }
  }
     class Circle extends Shape
{   
       private double radius;
       Circle(double r)
       {
          radius = r ;
       }
       public void area()
       {
         System.out.println("Area of Circle is = " + (Math.PI*radius*radius));
       }
}
    class InstanceofOperator
  {
            public static void main(String[] args)
      {
                Shape s; //Shape class reference variable
                Rectangle  r = new Rectangle(10,20);
                s = r; //Assign rectangle reference to shape reference
                if (s instanceof Rectangle)
                   System.out.println("Contain Reference to Rectangle Object");
               else
                   System.out.println("Contain Reference to some other Object");
      }
   }

instanceof Operator in Java Example