多型
編譯時的多型:方法多載
運行時的多型:動態系結
多型的三大前提
- 類之間要有繼承關系
- 要出現方法重寫
- 父類的參考指向了子類的物件
測驗樣例
// 定義Person類
public class Person {
public String name;
public String sex;
public int age;
public Person(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public void eat(){
System.out.println("Person => eat()");
}
}
// 定義Student類,繼承Person類
public class Student extends Person{
public int stuNum;
public int score;
public Student(String name, String sex, int age) {
super(name, sex, age);
}
public void study(){
System.out.println("Student => study()");
}
// 重寫父類方法
@Override
public void eat() {
System.out.println("Student => eat()");
}
}
// 測驗類(Application)
public class Application {
public static void main(String[] args) {
Person robot01 = new Student("robot01","female",18);
Person robot02 = new Person("robot02","male",18);
robot01.eat(); // Student => eat()
robot02.eat(); // Person => eat()
// robot01.study(),爆紅
}
}
多型的轉型
為什么需要轉型
? 當使用多型方式呼叫方法時,首先檢查父類中是否有該方法,如果沒有,則編譯錯誤,也就是說,不能呼叫子類擁有 而父類沒有的方法,編譯都錯誤,更別說運行了,所以,想要呼叫子類特有的方法,必須做向下轉型
向上轉型(父型別別 變數名 = 子類物件)
? 多型本身是子型別別向父型別別向上轉換的程序,這個程序是默認的,當父類參考指向一個子類物件時,便是向上轉型
向下轉型(子型別別 變數名 = (子型別別) 父類變數名)
? 父型別別向子型別別向下轉換的程序,這個程序是強制的,一個已經向上轉型的子類物件,將父類參考轉為子類參考,可以使用強制型別轉換的格式,便是向下轉型,
// 定義父類Draw
public class Draw {
public void drawPicture(){
System.out.println("Draw => draw()");
}
}
// 定義子類Circle
public class Circle extends Draw{
// 重寫父類方法
@Override
public void drawPicture() {
System.out.println("Circle => DrawCircle()");
}
// 子類獨有的方法
public void roll(){
System.out.println("Circle => roll()");
}
}
// 測驗類
public class Application {
public static void main(String[] args) {
// 向上轉型
Draw picture = new Circle();
// 只能使用被重寫的方法
picture.drawPicture(); // Circle => DrawCircle()
// 向下轉型
Circle circlePic = (Circle)picture;
// 可以使用子類自己的方法
picture.drawPicture(); // Circle => DrawCircle()
circlePic.roll(); // Circle => roll()
}
}
instance of 運算子
作用:判斷左面的物件是否是右面的類的實體,回傳值為bool型別
// 定義父類Father
public class Father {
public void say(){
System.out.println("I'm father!");
}
}
// 定義介面Eat
public interface Eat {
public void eat();
}
// 定義子類Son1,繼承父類Father以及介面Eat
public class Son1 extends Father implements Eat{
// 重寫父類方法
@Override
public void say() {
System.out.println("I'm son1!");
}
// 實作介面方法
@Override
public void eat() {
System.out.println("Son1 => eat()");
}
}
// 測驗類(Application)
public class Application {
public static void main(String[] args) {
Father robot01 = new Son1();
Eat robot02 = new Son1();
robot01.say(); // I'm son1!
robot02.eat(); // Son1 => eat()
System.out.println(robot01 instanceof Father); // true
System.out.println(robot01 instanceof Son1); // true
System.out.println(robot02 instanceof Father); // true
System.out.println(robot02 instanceof Son1); // true
}
}
多型的好處
- 限制類的使用者只能使用父類定義的方法,無法使用子類新定義的方法
- 可以擴展資料存盤的范圍
- 可以拓展方法的引數型別和回傳值型別
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549605.html
標籤:Java
上一篇:Disruptor-簡單使用
