What is the instanceof
operator used for? I\'ve seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
As mentioned in other answers, the canonical typical usage of instanceof
is for checking if an identifier is referring to a more specific type. Example:
Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
// then if someobject is in fact a button this block gets executed
} else {
// otherwise execute this block
}
Note however, that the type of the left-hand expression must be a parent type of the right hand expression (see JLS 15.20.2 and Java Puzzlers, #50, pp114). For example, the following will fail to compile:
public class Test {
public static void main(String [] args) {
System.out.println(new Test() instanceof String); // will fail to compile
}
}
This fails to compile with the message:
Test.java:6: error: inconvertible types
System.out.println(t instanceof String);
^
required: String
found: Test
1 error
As Test
is not a parent class of String
. OTOH, this compiles perfectly and prints false
as expected:
public class Test {
public static void main(String [] args) {
Object t = new Test();
// compiles fine since Object is a parent class to String
System.out.println(t instanceof String);
}
}