曬太陽

          關于instanceof的用法

          先看兩個小程序:
          1、
          1public class IntegerTypeTest {
          2    public static void main(String[] args){
          3        String str = "abc";
          4        boolean myBoolean = (str instanceof Integer); //compile time error
          5        System.out.println(myBoolean);
          6    }

          7}
          2、
           1     import java.util.*;
          public class InstanceOfDemo {
           2
           3    public static void main(String[] args) {
           4        System.out.println(new InstanceOfDemo() instanceof String); //compile time error
           5        System.out.println(new InstanceOfDemo() instanceof Exception); //compile time error
           6        System.out.println(new InstanceOfDemo() instanceof Object); //compilation and output true
           7        
           8        System.out.println(new InstanceOfDemo() instanceof List); //compilation and output false
           9    }

          10}

          11
          這兩個程序的編譯結果和我們預想的不一樣,第一個程序編譯結果是:

          第二個程序編譯結果是:

          產生這種錯誤的原因在于,instanceof運算符第一個操作數的類型應該是第二個操作數的父類、子類或者與第二個操作數的類型相同。否則編譯會出錯。

          posted on 2009-09-23 08:39 曬太陽 閱讀(333) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2009年9月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          文章檔案

          收藏夾

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 嵊泗县| 岗巴县| 昆山市| 高碑店市| 家居| 沾益县| 南木林县| 汝城县| 托克逊县| 迁安市| 射洪县| 阿鲁科尔沁旗| 大埔县| 大冶市| 曲周县| 武胜县| 安多县| 杨浦区| 江永县| 云南省| 和静县| 同江市| 霍邱县| 禹州市| 眉山市| 铁岭市| 太仓市| 扎赉特旗| 江油市| 昔阳县| 伊宁县| 淮南市| 会昌县| 襄樊市| 安多县| 武邑县| 剑阁县| 高尔夫| 天门市| 若尔盖县| 信丰县|