instanceof關鍵字例項與多型
阿新 • • 發佈:2021-12-11
instanceof關鍵字例項與多型
例項程式碼如下:
Application類
package com.han.duotai; /** * instanceof關鍵字例項,判斷引用型別是否屬於一個型別 * * 關於多型 * 1.父類的引用指向子類的物件 * 2.把子類轉換為父類,向上轉型 * 3.把父類轉換為子類,向下轉型,需要進行強制型別轉換 * 4.方便方法的呼叫,減少重複的程式碼 */ public class Application { public static void main(String[] args) { Object obj = new Student(); System.out.println(obj instanceof Person);//true System.out.println(obj instanceof Object);//true System.out.println(obj instanceof Student);//true System.out.println(obj instanceof Teacher);//false System.out.println(obj instanceof String);//false System.out.println("======================================="); Person person = new Student(); System.out.println(person instanceof Person);//true System.out.println(person instanceof Object);//true System.out.println(person instanceof Student);//true 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);//true //System.out.println(student instanceof Teacher);//編譯報錯 //System.out.println(student instanceof String);//編譯報錯 System.out.println("======================================="); Person person1 = new Student(); ((Student) person1).go();//高轉低-->強制型別轉換 } }
Person類
package com.han.duotai;
public class Person {
}
Student類
package com.han.duotai;
public class Student extends Person{
public void go(){
}
}
Teacher類
package com.han.duotai;
public class Teacher extends Person{
}