1. 程式人生 > 其它 >java 中 instanceof 與 型別轉換

java 中 instanceof 與 型別轉換

1,新建Application類,作為程式的入口

package oop.demo07;

/*
instanceof 與 型別轉換
    1,父類引用指向子類物件
    2,把子類轉換為父類,向上轉型
    3,把父類轉換為子類,向下轉型:強制轉換
    4,方便就去的呼叫,減少重複的程式碼,

    抽象:封裝、繼承、多型;
 */
public class Application {
    public static void main(String[] args) {
//        型別之間的轉換   父類   子類

//        高               低
        Person s1 = new Student();
//        強制型別轉換
        Student s2 = (Student) s1;
        s2.go();//go

        Student s3 = new Student();
        s3.go();//go
        s3.run();//run
        Person s4 = new Student();
        s4.run();//run
        ((Student) s4).go();//go

        System.out.println("===================");

        Object obj = new Student();

//        System.out.println(x instanceof  y); //能不能編譯通過

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

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


}

2,新建Person類

package oop.demo07;

public class Person {
    public  void  run(){
        System.out.println("run");
    }
}

3,新建Student類

package oop.demo07;

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

4,新建Teacher類

package oop.demo07;

public class Teacher extends Person {
}

5,執行結果