package com.oop.demo06;public class Person { public void run(){ System.out.println("run"); }} package com.oop.demo06;public class Student extends Pers ...
package com.oop.demo06;
public class Person {
public void run(){
System.out.println("run");
}
}
package com.oop.demo06;
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
/*
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) {
//Object->String
//Object->person->Teacher
//Object->Person->Student
Object object=new Student();
//System.out.println(x instanceof y);能不能編譯通過!就是看x和y之間是否存在父子關係
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);//flase
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);//編譯報錯
}
}
*/
/*
多態註意事項:
1、多態是方法的多態,屬性沒有多態
2、父類和子類有聯繫 類型轉換異常(ClassCastException)
3、存在條件:繼承關係,方法需要重寫,父類引用指向子類對象 Father f1=new son();
不能重寫,也沒有多態的方法
1、static 方法,屬於類,它不屬於示例
2、final 常量
3、private方法
*/
package com.oop.demo06;
public class Teacher extends Person{
}
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 s1=new Student();
//student這個對象轉換成Student類型,我們就可以使用Student類型的方法
Student student= (Student)s1;//高轉低強制轉換
//子類轉換成父類可能會丟失一些方法
Student s2=new Student();
s2.go();
Person person=student;
}
}
/*
1、父類引用指向子類對象
2、把子類轉換成父類,向上轉型
3、把父類轉換成子類,向下轉型,需強制轉換
4、方便方法的調用,減少重覆的代碼
*/