instanceof
"instanceof" is a Java keyword and a binary operator. It works on two operands, object reference on the left and class/interface name on the right. instanceof operator returns true if the object reference can be casted to the class/interface and false otherwise.
Syntax
<<object reference>> instanceof <<class/interface name>>
When to use instanceof
Let's say you've a situation that different kinds of objects (objects based on different classes) are part of an ArrayList. You've to iterate them and print the values. Please assume that you know all the class names that are part of ArrayList.
You can use instanceof operator to identify the compatible class for casting.
Explanation
import java.util.*;
interface X
{
}
class A implements X
{
int number;
A(int number)
{
this.number = number;
}
public int getNumber()
{
return this.number;
}
}
class B
{
int number;
B(int number)
{
this.number = number;
}
public int getNumber()
{
return this.number;
}
}
public class InstaceOfDemo
{
public static void main(String args[])
{
A obj1 = new A(10);
B obj2 = new B(20);
A obj3 = new A(30);
B obj4 = new B(40);
ArrayList list = new ArrayList();
list.add(obj1);
list.add(obj2);
list.add(obj3);
list.add(obj4);
for(int i=0;i< list.size();i++)
{
Object obj = list.get(i);
if(obj instanceof A)
{
A ob = (A)obj;
System.out.println("Number: "+ob.getNumber());
}
else if(obj instanceof B)
{
B ob = (B)obj;
System.out.println("Number: "+ob.getNumber());
}
}
System.out.println("obj1 instanceof A: "+(obj1 instanceof X));
System.out.println("obj2 instanceof B: "+(obj2 instanceof X));
}
}
- I've defined 1 interface named "X" and two classes named "A" and "B". Class A implements the interface "X". Both classes A and B have got a getNumber method which will return the instance variable value.
- Based on these two classes, I've added objects to ArrayList. In total, I've added 4 objects into the list, 2 objects belong to A and 2 belong to B.
- list.get(i) returns java.lang.Object. So, we're checking a condition to make sure casting can be done either with A or B.
- 4 output statements at the end can give you a quick idea of what instanceof can do at runtime.
>java InstaceOfDemo
Number: 10
Number: 20
Number: 30
Number: 40
obj1 instanceof A: true
obj2 instanceof B: false
obj1 instanceof java.lang.Object: true
obj2 instanceof java.lang.Object: true