1. 程式人生 > 其它 >40.instanceo和型別轉換

40.instanceo和型別轉換

instanceo

instanceo就是判斷前面是不是後面的型別

1.父類的引用指向子類的物件
2.把子類轉換為父類,向上轉型
3.把父類轉換為子類,向下轉型,需要強制轉換,可能會丟失方法
4.方便方法的呼叫,減少重複的程式碼,簡潔

抽象: 封裝,繼承,多型! 抽象類:介面
package com.instanceo;

import com.duotai.Student;

public class Demo40 {
public static void main(String[] args) {
//object>String
//object>person>teacher
//object >person>student
Object object = new Student();

// System.out.println(X instanceof Y); //能不能編譯通過

System.out.println(object instanceof Student);//ture
System.out.println(object instanceof Person);//false
System.out.println(object instanceof Object);//ture
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
System.out.println("===================================");

Person person = new com.instanceo.Student();
System.out.println(person instanceof com.instanceo.Student);//ture
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//ture
System.out.println(person instanceof Teacher);//false
// System.out.println(person instanceof String);//false

System.out.println("===================================");
com.instanceo.Student student = new com.instanceo.Student();
System.out.println(student instanceof com.instanceo.Student);//ture
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//ture
// System.out.println(student instanceof Teacher);//false
// System.out.println(student instanceof String);//false

//型別之間的轉換,基本型別轉換,高-低 父-子
//父-子
Person person1 = new com.instanceo.Student();

//將person1這個物件轉換為Student型別,我們就可以使用student型別的方法了
com.instanceo.Student student1 = (com.instanceo.Student)person1;
student1.go();

//子類轉換為父類;可能丟失自己的本來的一些方法
com.instanceo.Student student2 = new com.instanceo.Student();
student2.go();
Person person2 = student2;

}
}
/*
1.父類的引用指向子類的物件
2.把子類轉換為父類,向上轉型
3.把父類轉換為子類,向下轉型,需要強制轉換,可能會丟失方法
4.方便方法的呼叫,減少重複的程式碼,簡潔

抽象: 封裝,繼承,多型! 抽象類:介面

*/
package com.instanceo;

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

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