歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 深入Java關鍵字instanceof

深入Java關鍵字instanceof

日期:2017/3/1 9:32:49   编辑:Linux編程
深入Java關鍵字instanceof instanceof關鍵字用於判斷一個引用類型變量所指向的對象是否是一個類(或接口、抽象類、父類)的實例。 舉個例子:
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。

Copyright © Linux教程網 All Rights Reserved