instanceof 與 應用類型強轉

package com.moxi.wc;

/**
 * @author Mr.Wang
 * @version 1.0
 * @since 1.8
 */
public class Instan {
    // 一個關鍵詞instanceof
    public static void main(String[] args) {
        System.out.println(null instanceof Object); // null instanceof xxx 都是false
        // 以下有幾個類關係如下
        // Object => Student      Object => Personer   Object => String  Personer => Student
        // 第一種情況
        Student s = new Student();
        System.out.println(s instanceof Object);
        System.out.println(s instanceof Personer);
        System.out.println(s instanceof Student);
        /*System.out.println(s instanceof String);*/ // 編譯就報錯Student類類型和String沒有關係
        // 第二種情況
        Personer per = new Personer();
        System.out.println(per instanceof Object);
        System.out.println(per instanceof Personer);
        System.out.println(per instanceof Student);  // false 因爲per不是Student或Student子類的實例

        // 第三種情況
        Personer per2 = new Student(); // 結果和類型是Student一樣
        System.out.println(per2 instanceof Object);
        System.out.println(per2 instanceof Personer);
        System.out.println(per2 instanceof Student);  // true
    // 總結: instanceof 左邊是引用類型右邊是類,true: 說明該實例是右邊本身或者子類實例出來的,和什麼類型沒有關係(第三種)
    // 毫無關係的編譯就會報錯

    // ====================================>
    // 爲了方便類型轉換父類引用指向子類就是一種低轉高的例子,代價是子類特有的方法和屬性不能被調用
    // 父類向子類轉化必須是強轉((Student) Personer).子類的方法
    ((Student)per).keyboards();  // 報錯不能強制轉換,因爲實例不一樣,所以強轉之前用instanceof是個明智的選擇
    ((Student)per2).keyboards(); // 正常運行 (先姑且Personer類和Student類都有且是父子關係)
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章