1、總結java
1.多態:當子類對象賦值給父類對象後,經過父類對象調用成員方法,剛好子類重寫了這個成員方法,此時經過父類調用到的是子類的成員方法(若沒重寫則是繼承父類的方法)。函數
2.向上轉換的時候(Father的對象=Son的對象)不須要增強制類型轉換,也就是說子類對象能夠直接賦值給父類對象。
可是父類對象不能直接賦值給子類對象,向下轉換(Son的對象=Father的對象)的時候就須要增強制類型轉換,而且前提是Father對象來源於Son對象,也便是以下關係。當有多個子對象時須要藉助instanceof來判斷實例來源於哪一個類。
Father f = new Son();
Son s = (Son)f; /*約等效於:Son s = new Son()*/this
3.instanceof關鍵字:用來判斷一個對象是否是某個類的實例。
注意:全部的子類的對象均可以認爲是父類的實例。全部的子類對象在判斷 (子類對象實例 instanceof 父類類型) 的時候都是爲真的。spa
4.Object類是全部類的父類,它能夠作左值接收任何對象,可是不必定能表現出多態,由於Object中可能根本沒有實現你要多態的函數。code
5.當你重寫一個繼承來的成員方法時,訪問權限不能更weaker(eg:把繼承來的protected方法變爲private), 可是能夠更Stronger,例如把protected方法重寫爲public方法。對象
2、試驗Demoblog
/*Cnv4.java: Test Father=Son*/ class Father { private int money; public int getMoney() {return money; } public void setMoney(int money) {this.money = money; } public void printInfo() {System.out.println("This is Father");} } class Son extends Father{ public void printInfo() {System.out.println("This is son");} public void playGame() {System.out.println("playGame ...");} } class Daughter extends Father{ public void printInfo() {System.out.println("This is daughter");} } public class Cnv4 { public static void main (String args[]) { Father f = new Father(); Son s = new Son(); Daughter d = new Daughter(); print(f); print(s); print(d); } public static void print(Father f) { f.printInfo(); } }
/*Cnv5.java: Test Son=Father in printAction()*/ class Father { private int money; public int getMoney() {return money; } public void setMoney(int money) {this.money = money; } public void printInfo() {System.out.println("This is Father");} public void drink() {System.out.println("drink ...");} } class Son extends Father{ public void printInfo() {System.out.println("This is son");} public void playGame() {System.out.println("playGame ...");} } class Daughter extends Father{ public void printInfo() {System.out.println("This is daughter");} public void dance() {System.out.println("dance ...");} } public class Cnv5 { public static void main (String args[]) { Father f = new Father(); Son s = new Son(); Daughter d = new Daughter(); printAction(f); printAction(s); printAction(d); printAction_2(f); printAction_2(s); printAction_2(d); } public static void printAction(Father f) { /*Son --> Father --> Son*/ if (f instanceof Son) { Son son = (Son)f; son.playGame(); } else if (f instanceof Daughter) { Daughter d = (Daughter)f; d.dance(); } else if (f instanceof Father) { f.drink(); } } public static void printAction_2(Father f) { /*Son --> Father --> Son*/ if (f instanceof Father) { f.drink(); } else if (f instanceof Son) { Son son = (Son)f; son.playGame(); } else if (f instanceof Daughter) { Daughter d = (Daughter)f; d.dance(); } } }