JAVA进阶day04多态(向上转化,向下转化)
生活随笔
收集整理的這篇文章主要介紹了
JAVA进阶day04多态(向上转化,向下转化)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java多態讓我覺得比較繞的就應該是向上轉化跟向下轉化了。
一、向上轉化
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();}}向上轉化:我的理解是,父類有可繼承的方法A B 子類 甲中有A(覆寫的) B(覆寫的) C。 子類乙中有 A(覆寫的) B(覆寫的) D。子類丙中有 A(覆寫的) B(覆寫的) E。類似上上面的例子,如果共同調用父類中的函數呢?
是不是應該
這樣寫呢?這樣應該算作重載。我們使用多態就可以使用這個中向上轉化,來調用父類中共有的,如果子類中覆寫了,那么就去調用子類中的。是不是讓代碼更加整潔簡單?
二、向下轉化
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);}public static void printAction(Father f) {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();}}}想要在一個函數中調用父類中沒有的函數,那么使用的辦法就是先向上轉化然后在使用向下轉化。我們在向上轉化之后,再向下轉化時候要判斷是哪一個子類,然后才能轉化,這時候我們使用的就是 instanceof .
對于這種多態方式,就是知道有這么個好用的東西就行了,需要的時候打開過來再看看該怎么用就好。知識不是非要干死腦細胞,裝在腦子里才叫知識。隨著年紀增大,步入社會,有了家庭,更應該采用更加有效的方式學習累積。
總結
以上是生活随笔為你收集整理的JAVA进阶day04多态(向上转化,向下转化)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: modprobe: FATAL: Mod
- 下一篇: ML之LIME:基于boston波士顿房