instanceof和類型轉換

instanceof和類型轉換

instanceof:判斷A是否爲B本類或者子類的對象java

  • 例如:學習

    A (對象) instanceof B(類) 結果爲booleancode

    1. A和B比較以前會先判斷A能不能轉換成B類,能則經過,不能則編譯報錯
    2. 而後判斷A是否爲B本類或子類的對象,是就是true,反之就是false

例如:對象

public class zhixing {
    public static void main(String[] args) {
        //student是實際類型,Object是引用類型
        Object object = new student();
        System.out.println(object instanceof student);//true
        System.out.println(object instanceof Person);//true
        System.out.println(object instanceof Object);//true
        System.out.println(object instanceof teacher);//false,由於object不是teacher本類或子類的對象
        System.out.println(object instanceof String);//false,由於object不是String本類或子類的對象
        Person person = new student();
        System.out.println(person instanceof student);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Object);//true
        System.out.println(person instanceof teacher);//false,由於person不是teacher本類或子類的對象
        //System.out.println(person instanceof String);//爲何直接報錯,由於person類不能轉換爲String類,由於二者沒有父子關係
        student student = new student();
        System.out.println(student instanceof student);//true
        System.out.println(student instanceof Person);//true
        System.out.println(student instanceof Object);//true
        //System.out.println(student instanceof teacher);//student不能轉換爲teacher,由於無父子關係
        //System.out.println(student instanceof String);//student不能轉換爲String,由於無父子關係
    }
}

類型之間的轉換

  • 以前學習的是基本類型的轉換,如今學習的是引用類型得轉換編譯

    在引用類型之間的轉換,父類就是高,子類就是低,低轉高是自動轉換,高轉低是強制轉換class

    子類轉父類可能會丟失一些本身原本的方法object

  • 把子類轉換爲父類,向上轉型引用

    把父類轉換爲子類,向下轉型,可能會丟失一些方法(強制轉換)方法

    類型轉換的好處:方便方法的調用,減小重複的代碼static

舉例說明:

public class zhixing {
    public static void main(String[] args) {
        Person obj = new student();
        //將obj強轉爲student類型,如今就能夠調用student類中的方法
        ((student) obj).go();
    }
}
相關文章
相關標籤/搜索