July 18, 2022

instanceof Operator in Java

instanceof operator in Java is used to test the type of an object during run time.

The syntax of Java instanceof operator is as follows.

objRef instanceof objType

Here objRef is a reference to an instance.

objType denotes a class type.

Using instanceof operator you can check if objRef is of the type objType or not. If yes the instanceof operator returns true otherwise false.

Using instanceof operator in Java

instanceof operator can help in preventing ClassCastException at run time.

For example a parent class reference can refer to child class but the opposite, child class referring to parent class, results in compile time error without type casting.

Child c = new Parent(); // Compile time error

// Ok with downcasting, may result in ClassCastException
Child c = (Child) new Parent();

This down casting (parent to child) will result in ClassCastException if there are more than one children and you are trying to cast with out knowing the actual type. This scenario is shown in the following Java example where we have two child classes Child and AnotherChild. In the method methodToCast you are trying to cast to Child even when the AnotherChild reference is passed resulting in ClassCastException.

public class Test {
  public static void main(String[] args) {
    Child c = new Child();
    Parent p = new Parent();
    AnotherChild ac = new AnotherChild();
    // ok, upcasting to parent reference
    p = c;
    methodToCast(c);
    methodToCast(ac);
  }
	
  private static void methodToCast(Parent p) {
    Child c = (Child)p;
  }	
}

class Parent {
  public void method1() {
    System.out.println("In method");
  }
}

class Child extends Parent {
  public void method1() {
    System.out.println("In child method");
  }
}

class AnotherChild extends Parent {
  public void method1() {
    System.out.println("In Anotherchild method");
  }
}
Output
Exception in thread "main" java.lang.ClassCastException: com.knpcode.programs.AnotherChild cannot be cast to com.knpcode.programs.Child
	at com.knpcode.programs.Test.methodToCast(Test.java:15)
	at com.knpcode.programs.Test.main(Test.java:11)

In such scenario you need to use instanceof operator to check the type of the reference.

private static void methodToCast(Parent p) {
  if(p instanceof Child) {
    Child c = (Child)p;
  }
}

Consider another scenario where you have multi-level inheritance.

public class Test {
  public static void main(String[] args) {
    Parent p = new Parent();
    Child c = new Child();
    AnotherChild ac = new AnotherChild();
    GrandChild gc = new GrandChild();
    methodToCast(c);
    methodToCast(gc);
    methodToCast(ac);
  }
	
  private static void methodToCast(Parent p) {
    Child c = (Child)p;
    c.method1();
  }
}

class Parent {
  public void method1() {
    System.out.println("In Parent method");
  }
}

class Child extends Parent {
  public void method1() {
    System.out.println("In Child method");
  }
}

class AnotherChild extends Parent {
  public void method1() {
    System.out.println("In Anotherchild method");
  }
}

class GrandChild extends Child {
  public void method1() {
    System.out.println("In GrandChild method");
  }
}
Output
In Child method
In GrandChild method
Exception in thread "main" java.lang.ClassCastException: com.knpcode.programs.AnotherChild cannot be cast to com.knpcode.programs.Child
	at com.knpcode.programs.Test.methodToCast(Test.java:15)
	at com.knpcode.programs.Test.main(Test.java:11)

As you can see casting works for Child and GrandChild (as it is also of type Child) but throws ClassCastException for AnotherChild which is of type Parent. In this scenario checking for the type using the instanceof operator ensures that the method is called only for Child types references.

private static void methodToCast(Parent p) {
  if(p instanceof Child) {
    Child c = (Child)p;
    c.method1();
  }
}

Points about instanceof operator in Java

1- If object reference is null instanceof operator returns false.

public class Test {
  public static void main(String[] args) {
    Test obj = null;
    if(obj instanceof Test) {
      System.out.println("instance of operator returns true");
    }else {
      System.out.println("instance of operator returns false");
    }
  }
}
Output
instance of operator returns false

2- Testing with instanceof operator with Object class always returns true as Object class is super class of all the classes in Java.

public class Test {
  public static void main(String[] args) {
    Test obj = new Test();
    Parent p = new Parent();
    if(obj instanceof Object) {
      System.out.println("instance of operator returns true");
    }else {
      System.out.println("instance of operator returns false");
    }
    
    if(p instanceof Object) {
      System.out.println("instance of operator returns true");
    }else {
      System.out.println("instance of operator returns false");
    }
  }
}

class Parent {
  public void method1() {
    System.out.println("In Parent method");
  }
}
Output
instance of operator returns true
instance of operator returns true

That's all for the topic instanceof Operator in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment