【Java】繼承、介面、抽象類、多型之間的關係和區別 【二】
阿新 • • 發佈:2019-01-09
多型:執行時引用指向子元素的例項物件【jvm記憶體模型很重要,也是入門的基礎】
接著上面繼續理解,建立一個老師類
package com.physical; public class Teacher extends Person{ String profession; int teacherid; //一個無參的構造器 Teacher(){ } //有參的構造器 Teacher(int teacherid,String sname){ super(teacherid,sname); } @Override void toDoThings() { System.out.println("我叫"+sname+"身份證號是:"+idcard+"是一名"+profession+"工號是"+teacherid); } @Override void eatFood() { System.out.println("我是一名老師"); System.out.println("每天一日三餐很規律"); System.out.println("時間允許的條件下,我還會打下太極"); } }
實現結果
package com.physical; public class Test { public static void main(String[] args) { Person p=null; Student stu=new Student(123456789,"Joncky"); stu.profession="學生"; stu.stuid=001; p=stu; p.toDoThings(); p.eatFood(); Teacher t=new Teacher(987654321,"bear"); t.profession="老師"; t.teacherid=985986; p=t; p.eatFood(); p.toDoThings(); } }
其實多型實現了執行時的動態繫結JAVA引用變數有兩個型別:一個是編譯時的型別,一個是執行時的型別,編譯時的型別由宣告該變數時使用的型別決定,執行時的型別由實際賦給該變數的物件決定。如果編譯時型別和執行時型別不一致,就會出現所謂的多型(Polymorphism)。
更好的例子請見:https://zhidao.baidu.com/question/345445792.html