instanceof和型別轉換
instanceof:判斷A是否為B本類或者子類的物件
-
例如:
A (物件) instanceof B(類) 結果為boolean
- A和B比較之前會先判斷A能不能轉換成B類,能則通過,不能則編譯報錯
- 然后判斷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,因為無父子關系
}
}
型別之間的轉換
-
之前學習的是基本型別的轉換,現在學習的是參考型別得轉換
在參考型別之間的轉換,父類就是高,子類就是低,低轉高是自動轉換,高轉低是強制轉換
子類轉父類可能會丟失一些自己本來的方法
-
把子類轉換為父類,向上轉型
把父類轉換為子類,向下轉型,可能會丟失一些方法(強制轉換)
型別轉換的好處:方便方法的呼叫,減少重復的代碼
舉例說明:
public class zhixing {
public static void main(String[] args) {
Person obj = new student();
//將obj強轉為student型別,現在就可以呼叫student類中的方法
((student) obj).go();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/256200.html
標籤:其他
