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"); } }輸出結果:
true true true true另外,數組類型也可以使用instanceof來比較。比如 String str[] = new String[2]; 則str instanceof String[]將返回true。