Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.
Example:
public class Test
{
public static void main(String [] args)
{
Mammal[] obj = new Mammal[3];
obj[0] = new Mammal(50);
obj[1] = new Human(30, 2);
obj[2] = new Human(80, 5);
for(int i=0; i<3; i++)
System.out.println(obj[i]);
for(int i=0; i<3; i++)
{
if(obj[i] instanceof Human)
{
Human objH = (Human)obj[i];
objH.drinkMotherMilk();
System.out.println(objH.thinkCreative());
System.out.println(objH);
}
}
for(int i=0; i<3; i++)
System.out.println(obj[i]);
}
}
|
Output:
|
Example:
Human h = null;
if(h instanceof Human)
System.out.println("h is an instance of Human");
else
System.out.println("h is not an instance of
Human");
// It is not.
Human x = new Human();
if(x instanceof Human)
System.out.println("x is an instance of Human");
else
System.out.println("x is not an instance of
Human");
//Yes. it is.
Mammal y = new Human();
if(y instanceof Human)
System.out.println("y is an instance of Human");
else
System.out.println("y is not an instance of
Human");
//Yes. it is.
Mammal z = new Mammal();
if(z instanceof Human)
System.out.println("z is an instance of Human");
else
System.out.println("z is not an instance of
Human");
// It is not.