(Java學習筆記)instanceof和isInstance比較
阿新 • • 發佈:2018-12-13
前提條件:
class Father{}
class Child extends Father{}
Father father = new Father();
Child child = new Child();
Father child_father = new Child();
1.instanceof:
由這段程式碼可見,子類instanceof父類,判斷結果為true。
child instanceof Child//true
child instanceof Father//true
我們再看這段程式碼,父類instanceof子類,判斷結果為false
System.out.println(father instanceof Child);
那麼我們或許會有疑問,instanceof比較的究竟是引用還是例項,看下面這段程式碼就會有所瞭解,他的所有表現都跟其例項一樣
System.out.println(child_father instanceof Child);//ture
System.out.println(child_father instanceof Father);//true
由於null不是任何類的子類,所以結果false。注意instanceof後面的必須為一個Class,不能為null
null instanceof Object
2.isInstance 對於isInstance,我們可以看到如下所示
System.out.println(child.getClass().isInstance(child));//true System.out.println(child.getClass().isInstance(father));//false Child child2 = new Child(); System.out.println(child.getClass().isInstance(child2));//true System.out.println(father.getClass().isInstance(child));//true
同樣,他比較的也是其例項
System.out.println(child_father.getClass().isInstance(child));//true
System.out.println(child_father.getClass().isInstance(father));//false
總結:(待補充)