What is the instanceof operator used for? I\'ve seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
As described on this site:
The
instanceofoperator 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 --> trueHowever, applying
instanceofon a null reference variable/expression returns false.String s = null; return s instanceof String; //result --> falseSince a subclass is a 'type' of its superclass, you can use the
instanceofto 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!