天天看點

JavaSe面向對象09:instanceof和類型轉換(筆記)

視訊學習位址

點我跳轉ψ(`∇´)ψ

前言

instanceof可以判斷兩個類之間是否存在繼承關系
public class Application {
    public static void main(String[] args) {
        //Object > String
        //Object > Person > Teacher
        //Object > Person > Student

        Object o = new Student();
        System.out.println(o instanceof Student);   //true
        System.out.println(o instanceof Person);    //true
        System.out.println(o instanceof Object);    //true
        System.out.println(o instanceof Teacher);   //false
        System.out.println(o instanceof String);    //false

        Person p = new Student();
        System.out.println(p instanceof Student);   //true
        System.out.println(p instanceof Person);    //true
        System.out.println(p instanceof Object);    //true
        System.out.println(p instanceof Teacher);   //false
        //System.out.println(p instanceof String);    編譯報錯

        Student s = new Student();
        System.out.println(s instanceof Student);   //true
        System.out.println(s instanceof Person);    //true
        System.out.println(s instanceof Object);    //true
        //System.out.println(s instanceof Teacher);   編譯報錯
        //System.out.println(s instanceof String);    編譯報錯
    }
}
           

總結一句話就是編譯是否通過看左邊的引用類型和被instanceof的類型是否存在繼承關系,如果編譯通過則看右邊的被new的類對象是否存在繼承關系,存在為true,反之為false。

類型轉換

public class Application {
    public static void main(String[] args) {
        //高           低
        Person p = new Student();
        Student s = (Student) p;    //這個是高轉低,需要強制轉換
        s.go();                     //可以和上面一步到位寫成((Student) p).go();

        //同類型          同類型
        Student s2 = new Student();         
        Person p2 = s2;     //這個是低轉高,子類轉換為父類,會丢失自己的一些方法
        p2.run();           //可以和上面一步到位寫成((Person) s2).run(); 
    }
}
           
public class Person {
    public void run(){
        System.out.println("run");
    }
}

           
public class Student extends Person{
    public void go(){
        System.out.println("go");
    }
}


           

總結

  • 父類引用指向子類的對象
  • 子類轉換為父類,向上轉型
  • 父類轉換為子類,向下轉型,需要強制轉換
  • 友善方法的調用,減少重複的代碼,簡潔