The instanceof keyword is used to determine whether the object pointed to by a reference type variable is an instance of a class (or interface, abstract class, parent class).
For example:
The code copy is as follows:
public interface IObject {
}
public class Foo implements IObject{
}
public class Test extends Foo{
}
public class MultiStateTest {
public static void main(String args[]){
test();
}
public static void test(){
IObject f=new Test();
if(f instanceof java.lang.Object)System.out.println("true");
if(f instanceof Foo)System.out.println("true");
if(f instanceof Test)System.out.println("true");
if(f instanceof IObject)System.out.println("true");
}
}
Output result:
The code copy is as follows:
true
true
true
true
In addition, array types can also be compared using instanceof. For example, copy the code as follows:
String str[] = new String[2];
Then str instanceof String[] will return true.