Two usage instances of the Java keyword instanceof
- 2020-04-01 03:45:39
- OfStack
The instanceof keyword is used to determine whether the object to which a reference type variable points is an instanceof a class (or interface, abstract class, parent class).
For example:
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 results:
true
true
true
true
Also, array types can be compared using instanceof. Such as
String str[] = new String[2];
STR instanceof String[] returns true.