411 REFERENCE · Wikibooks
Java Programming/Keywords/instanceof
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
is a keyword.
It checks if an object reference is an instance of a type, and returns a boolean value;
The <object-reference> will return true for all non-null object references, since all Java objects are inherited from . will always return if <object-reference> is .
Syntax:
<object-reference> TypeName
For example:
class Fruit
{
//...
}
class Apple extends Fruit
{
//...
}
class Orange extends Fruit
{
//...
}
public class Test
{
public static void main(String[] args)
{
Collection<Object> coll = new ArrayList<Object>();
Apple app1 = new Apple();
Apple app2 = new Apple();
coll.add(app1);
coll.add(app2);
Orange or1 = new Orange();
Orange or2 = new Orange();
coll.add(or1);
coll.add(or2);
printColl(coll);
}
private static String printColl( Collection<?> coll )
{
for (Object obj : coll)
{
if ( obj instanceof Object )
{
System.out.print("It is a Java Object and");
}
if ( obj instanceof Fruit )
{
System.out.print("It is a Fruit and");
}
if ( obj instanceof Apple )
{
System.out.println("it is an Apple");
}
if ( obj instanceof Orange )
{
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 operator can also be applied to interfaces.
For example, if the example above was enhanced with the interface
interface Edible
{
//...
}
and the classes modified such that they implemented this interface
class Orange extends Fruit implements Edible
{
...
}
we could ask if our object were edible.
if ( obj instanceof Edible )
{
System.out.println("it is edible");
}
deep