人生苦短我學Java-9-面向物件三大特性之多型
阿新 • • 發佈:2022-01-03
一、多型
1、什麼是多型?
- 多種形態
- 是指一個物件在不同時刻,表現出來不同的狀態
- 比如說,水滴,液態、氣態、固態。
2、多型的前提條件
- 要有繼承關係
- 要有方法重寫
- 要有父類引用指向子類物件
口訣:
1.在多型,成員變數/靜態方法/靜態變數 編譯、執行看左邊。
2.在多型,方法重寫編譯看左邊、執行看右邊。
package com.ppl.day; /* com.ppl.day:學習專案 @user:廣深-小龍 @date:2022/1/3 15:51 */ /* 口訣: 1.在多型,成員變數/靜態方法/靜態變數 編譯、執行看左邊。 2.在多型,方法重寫編譯看左邊、執行看右邊。 */ public class Day13 {public static void main(String[] args) { Fu1 f = new Zi1(); System.out.println(f.i); System.out.println(f.j); // Fu1 沒有變數 j f.print(); f.printFu(); } } class Fu1 { int i = 1; int j = 3; public void printFu() { System.out.println("printFu"); }public void print() { System.out.println("Fu1"); } } class Zi1 extends Fu1 { int j = 2; public void print() { System.out.println("Zi1"); } }
輸出:
1
3
Zi1
printFu
3、多型的優劣
優點:
- 提高程式碼擴充套件性
- 父類引用作為形式引數,子類物件作為實際引數
/* 多型的應用 1.提高程式碼擴充套件性 2.父類引用作為形式引數,子類物件作為實際引數 */ class Anima {public void eat() { } } class AnimalTool { // 繼承結合多型的應用,一個工具類的方法即可 public static void print(Anima anima) { anima.eat(); } // 原每個子類呼叫時,都需要+一個工具類方法 // public static void print(Cat cat) { // cat.eat(); // } // public static void print(Dog dog) { // dog.eat(); // } } class Cat extends Anima { public void eat() { System.out.println("貓吃魚..."); } } class Dog extends Anima { public void eat() { System.out.println("狗啃骨頭..."); } }
缺點:
- 父類引用不能使用子類中的內容,解決:向下轉型
package com.ppl.day; /* com.ppl.day:學習專案 @user:廣深-小龍 @date:2022/1/3 16:46 */ public class Day14 { public static void main(String[] args) { PPerson p = new Student(); // 向上轉型 p.eat(); // 吃 // p.play(); // 編譯看左邊,左邊p沒該方法,所以報錯,需要向下轉型 Student s = (Student) p; // 向下轉型 s.play(); } } class PPerson { public void eat() { System.out.println("吃..."); } } class Student extends PPerson { public void eat() { System.out.println("學生吃麵條..."); } public void play() { System.out.println("學生玩遊戲..."); } }
注意:PPerson p = new Student(); // 向上轉型
向下轉型時必須是Student x = (Student)p,不能是其它;否則執行時報錯,編譯不會報錯。ClassCastException
多型:同一個物件在不同時刻表現不同的狀態。可上下轉型。如狗 --> 動物 --> 生物
歡迎來大家QQ交流群一起學習:482713805,博主微信+:gogsxl