Java多態的實作機制是什麼
Java中實作多態的機制是依賴父類別或介面的參考指向子類,從而實現一個物件多種形態的特性,其父類別的引用是在運行時動態的指向具體的實例,調用該引用的方法時,不是根據引用變數的類型中定義的方法來運行,而是根據具體的實例的方法。
簡單的範例
Person.java
import java.util.Scanner; public class Person { public int salary; public int allSalary(){ return 0; } public static void main(String[] args) { Person p = null; for (int n = 0; n < 3; n++) { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); System.out.println("请输入一个1-3的数字:\n1 is Teacher\n2 is Scientis\n3 is Waiter"); int i = sc.nextInt(); //分别指向了不同的子类,输出的结果是不一样的 if (i == 1) { p = new Teacher(5000); System.out.println(p.allSalary()); } else if (i == 2) { p = new Scientist(5000); System.out.println(p.allSalary()); } else if (i == 3) { p = new Waiter(5000); System.out.println(p.allSalary()); } else { System.out.println("?\n请输入1-3"); } } } }
Scientist .java
public class Scientist extends Person{ public Scientist(int salary){ this.salary = salary; } public int allSalary(){ int aa = salary*12+36500; System.out.print("五五开一年的工资:"); return aa; } }
# Waiter.java
public class Waiter extends Person{ public Waiter(int salary){ this.salary = salary; } public int allSalary(){ int aa = salary*12; System.out.print("服务员一年的工资:"); return aa; } }
Teacher .java
public class Teacher extends Person{ public Teacher(int salary){ this.salary = salary; } public int allSalary(){ int aa = salary*12+3650; System.out.print("教师一年的工资:"); return aa; } }
推薦教學:《Java教學》
以上是Java 實作多型的機制是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!