方法的重寫(重點) 多型
阿新 • • 發佈:2020-12-18
重寫:需要有繼承關係,子類重寫父類的方法!
1.方法名必須相同
2.引數列表必須系統
3.修飾符:範圍可以擴大但不能縮小:public>protected>default>private
4.丟擲的異常:範圍,可以被縮小,但不能擴大:ClassNotFoundException-->Exception(大)
重寫:子類的方法和父類必須要一致,方法體不同!
為什麼需要重寫:
1.父類的功能:子類不一定需要或不一定滿足!
alt+ins:override
package oop.demo07; public class Person {public void run(){ System.out.println("run"); } }
package oop.demo07; public class Student extends Person { }
package oop.demo07; public class Teacher extends Person{ }
package oop; import oop.demo07.Person; import oop.demo07.Student; import oop.demo07.Teacher; public class Application {//靜態方法和非靜態方法區別很大! //靜態方法: //方法的呼叫之和左邊,定義的資料型別有關 //非靜態:重寫 public static void main(String[] args) { //Object>Person>Student //Object>Person>Teacher //Object>String Object object = new Student(); System.out.println(object instanceof Student);//true System.out.println(object instanceofPerson);//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);//編譯報錯 } }
System.out,println(X instanceof Y);//能不能編譯通過 取決於XY之間是否有父子關係
package oop.demo07; public class Person { public void run(){ System.out.println("run"); } }
package oop.demo07; public class Student extends Person { public void go(){ System.out.println("go"); } }
package oop.demo07; public class Teacher extends Person{ }
package oop; import oop.demo07.Person; import oop.demo07.Student; import oop.demo07.Teacher; public class Application { //靜態方法和非靜態方法區別很大! //靜態方法: //方法的呼叫之和左邊,定義的資料型別有關 //非靜態:重寫 public static void main(String[] args) { //型別之間的轉化: 父 子 //高 低 Person obj = new Student(); //student將這個物件轉換為Student型別,我們就可以使用Student型別的方法了 //子類轉換為父類可能會丟失一些方法 Student student = new Student(); student.go(); Person person=student; person.run(); //低 高 //強制型別轉換另一種寫法((Student) obj).go(); } }
1.父類引用指向子類的物件
2.把子類轉換為父類,向上轉型
3.把父類轉換為子類,向下轉型,強制轉換
4.方便方法的呼叫,減少重複的程式碼!
抽象三大特性:1.封裝、繼承、多型!static