Java面向對象之instanceof和類型轉換
instanceof
- instanceof(類型轉換):利用此關鍵字可以判斷某一個對象是否是指定類的實例
格式:
對象 instanceof 類 返回boolean型
- 如果某個對象是某個類的實例,就返回true,否則返回false。
對象的多態性:指的是發生在繼承關系類之中,子類和父類之間的轉換。
- 向上轉型(自動完成):父類 父類對象 = 子類實例;
- 向下轉型(強制完成):子類 子類對象 = (子類)父類實例;
package OOP.Demo09;
public class Application {
public static void main(String[] args) {
//Object > String
//Object > Person > Student
//Object > Person > Teacher
//System.out.println(X instanceof Y);//能不能編譯通過!通過:X和Y之間是否存在父子關系
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
System.out.println(object instanceof String);//false
System.out.println("=================================");
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
//System.out.println(person instanceof String);//編譯報錯
System.out.println("=================================");
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);//編譯報錯
//System.out.println(student instanceof String);//編譯報錯
}
}
類型轉換
- 父類引用指向子類的對象
- 把子類轉換為父類,向上轉型;
- 把父類轉換為子類,向下轉型——需要強制轉換(可能會丟失一些方法)
- 方便方法的調用,減少重復的代碼
萬物皆有裂隙,那是光照進來的地方。
@側耳聽智慧,專心求聰明 Turnging your ear to wisdom and applying your heart to understanding!

浙公網安備 33010602011771號