What is the instanceof
operator used for? I\'ve seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
As described on this site:
The
instanceof
operator can be used to test if an object is of a specific type...if (objectReference instanceof type)
A quick example:
String s = "Hello World!" return s instanceof String; //result --> true
However, applying
instanceof
on a null reference variable/expression returns false.String s = null; return s instanceof String; //result --> false
Since a subclass is a 'type' of its superclass, you can use the
instanceof
to verify this...class Parent { public Parent() {} } class Child extends Parent { public Child() { super(); } } public class Main { public static void main(String[] args) { Child child = new Child(); System.out.println( child instanceof Parent ); } } //result --> true
I hope this helps!