Let’s learn what is instanceof in java?
instanceof java
instanceof operator is used to check whether the object is an instance of specified type. Type can be a class or a subclass or an interface.
instanceof operator returns either true or false. It is also known as comparison operator. Let’s see instanceof java example.
public class Example { public static void main(String[] args) { Example obj = new Example(); System.out.println(obj instanceof Example); } }
Output:
true
Let’s see an example for – an object of subclass type is also a type of parent class.
class Parent { } class Child extends Parent { public static void main(String[] args) { Child c = new Child(); System.out.println(c instanceof Parent); } }
Output:
true
instanceof with null
instanceof operator with a variable that has null value returns false. Let’s see an example where instanceof operator with variable has null value.
class Example { public static void main(String[] args) { Example obj = null; System.out.println(obj instanceof Example); } }
Output:
false
instanceof – downcasting and upcasting
Upcasting means when Superclass type refers to an object of Subclass or child class. For example
class Parent { } class child extends Parent{ } public class TestExample { public static void main(String[] args) { Parent obj = new child();// upcasting System.out.println(obj instanceof Parent); } }
Output:
true
In the above case reference variable “obj” contains an object of child. Using instanceof operator is “obj” object of class Parent. Output is true. Because object of Subclass class child is also an object of Superclass Parent.
Downcasting means when Subclass type refers to the object of Parent class. For example.
class Parent{ } class child extends Parent{ } public class TestExample { public static void main(String[] args) { Parent obj1 = new Parent(); child obj2 = (child) obj1;// downcasting } }
Output:
Exception in thread “main” java.lang.ClassCastException: class Parent cannot be cast to class child
Using instanceof operator we can avoid above exception like this.
class Parent{ } class child extends Parent{ } public class TestExample { public static void main(String[] args) { Parent obj1 = new Parent(); if(obj1 instanceof child) { child obj2 = (child) obj1; System.out.println(obj2); } else { System.out.println("Typecasting is not possible."); } } }
Output:
Typecasting is not possible.