1. 程式人生 > 其它 >面向物件13instanceof和型別轉換

面向物件13instanceof和型別轉換

package com.oop;

import com.oop.demo06.Person;
import com.oop.demo06.Student;
import com.oop.demo06.Teacher;

public class Application {
public static void main(String[] args) {
//型別之間的轉換:父 子
//
// //高 //底
// Person obj = new Student();
//
// //student將這個物件轉換為Studnet型別,我們就可以使用Student型別的方法了!
//
// Student student = (Student) obj;
// student.go();

//子類轉換為夫父類,可能對視自己的本來的一些方法!
Student student = new Student();
student.go();
Person person = student;


}

}

/*
1.父類引用指向子類的物件
2.把子類轉換為父類,向上轉型;
3.把父類轉換為子類,向下轉型;強制轉換,
4.方便方法的呼叫,減少重複的程式碼!簡介

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


package com.oop.demo06;

public class Person {

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

/*
多型注意事項:
1.多型是方法的多型,屬性沒有多型
2.父類和子類,有聯絡 型別轉換異常!ClassCastException!
3.存在條件:繼承關係,方法需要重寫,父類引用指向子類物件! Father f1 = new Son();

1.static 方法,屬於類,它不屬於例項
2.final 常量;
3.private方法;
*/


package com.oop.demo06;

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

}

/*
//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object object = new Student();

//System.out.println(X instanceof Y);//能不能編譯通過!是看XY之間有沒有父子之間的關係。

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 Person();
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);//編譯報錯!
*/


package com.oop.demo06;

public class Teacher extends Person{
}