Jump to content
Wikibooks The Free Textbook Project

Java Programming/Keywords/instanceof

From Wikibooks, open books for an open world

instanceof is a keyword.

It checks if an object reference is an instance of a type, and returns a boolean value;

The <object-reference> instanceof Object will return true for all non-null object references, since all Java objects are inherited from Object . instanceof will always return false if <object-reference> is null .

Syntax:

<object-reference> instanceof  TypeName

For example:

Computer code
class Fruit
{
//...	
}
class AppleextendsFruit
{
//...
}
class OrangeextendsFruit
{
//...
}
publicclass Test
{
publicstaticvoidmain(String[]args)
{
Collection<Object>coll=newArrayList<Object>();

Appleapp1=newApple();
Appleapp2=newApple();
coll.add(app1);
coll.add(app2);

Orangeor1=newOrange();
Orangeor2=newOrange();
coll.add(or1);
coll.add(or2);

printColl(coll);
}

privatestaticStringprintColl(Collection<?>coll)
{
for(Objectobj:coll)
{
if(objinstanceofObject)
{
System.out.print("It is a Java Object and");
}
if(objinstanceofFruit)
{
System.out.print("It is a Fruit and");
}
if(objinstanceofApple)
{
System.out.println("it is an Apple");
}
if(objinstanceofOrange)
{
System.out.println("it is an Orange");
}
}
}
}

Run the program:

java Test

The output:

"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Orange"
"It is a Java Object and It is a Fruit and it is an Orange"

Note that the instanceof operator can also be applied to interfaces. For example, if the example above was enhanced with the interface


Computer code
interface Edible
{
//...
}


and the classes modified such that they implemented this interface


Computer code
class OrangeextendsFruitimplementsEdible
{
...
}


we could ask if our object were edible.


Computer code
if(objinstanceofEdible)
{
System.out.println("it is edible");
}

AltStyle によって変換されたページ (->オリジナル) /