What is the instanceof
operator used for? I\'ve seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
Very simple code example:
If (object1 instanceof Class1) {
// do something
} else if (object1 instanceof Class2) {
// do something different
}
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
can be written as
if(ob instanceOf ClassA) {
}
public class Animal{ float age; }
public class Lion extends Animal { int claws;}
public class Jungle {
public static void main(String args[]) {
Animal animal = new Animal();
Animal animal2 = new Lion();
Lion lion = new Lion();
Animal animal3 = new Animal();
Lion lion2 = new Animal(); //won't compile (can't reference super class object with sub class reference variable)
if(animal instanceof Lion) //false
if(animal2 instanceof Lion) //true
if(lion insanceof Lion) //true
if(animal3 instanceof Animal) //true
}
}
The instanceof operator is used to check whether the object is an instance of the specified type. (class or subclass or interface).
The instanceof is also known as type comparison operator because it compares the instance with type. It returns either true or false.
class Simple1 {
public static void main(String args[]) {
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
If we apply the instanceof operator with any variable that has null value, it returns false.
class Test48{
public static void main (String args[]){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}
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!