Java 多態
多態是同一個行爲具有多個不同表現形式或形態的能力。
多態就是同一個接口,使用不同的實例而執行不同操作,如圖所示:
多態性是對象多種表現形式的體現。
現實中,比如我們按下 F1 鍵這個動作:
- 如果當前在 Flash 界面下彈出的就是 AS 3 的幫助文檔;
- 如果當前在 Word 下彈出的就是 Word 幫助;
- 在 Windows 下彈出的就是 Windows 幫助和支持。
同一個事件發生在不同的對象上會產生不同的結果。
多態的優點
- 1. 消除類型之間的耦合關係
- 2. 可替換性
- 3. 可擴充性
- 4. 接口性
- 5. 靈活性
- 6. 簡化性
多態存在的三個必要條件
- 繼承
- 重寫
- 父類引用指向子類對象
多態:
* 1.編譯時多態:一個接口(方法),多種實現(方法的重載)
* 2.運行時多態:父類可以接收子類對象
*
* 多態的作用:屏蔽子類差異化,寫出通用的代碼
* 運行時多態的前提是建立在繼承的基礎之上!
public class Main {
public static class Bird {
public void fly() {
System.out.println("飛揚的小鳥");
}
}
public static class Chicken extends Bird{
public void fly() {
System.out.println("一隻性感的小雞");
}
}
public static class Duck extends Bird{
public void fly() {
System.out.println("用心做鴨");
}
}
public static class Goose extends Bird{
public void fly() {
System.out.println("紅燒大鵝");
}
}
public static void main(String[] args) {
Bird bird = new Bird();
Chicken chicken = new Chicken();
Duck duck = new Duck();
Goose goose = new Goose();
//方式1:
bird.fly();
chicken.fly();
duck.fly();
goose.fly();
//方式2:
// 這裏 體現了多態
//利用父類接收了不同的子類對象
Bird[] birds = {bird, chicken, duck, goose};
for(int i = 0; i < birds.length; i++) {
Bird b = birds[i];
b.fly();
}
}
}
運行結果:
//練習 /*小男孩遛狗 *Boy類: 遛狗 *黃狗類: 跑(佔地盤) *黑狗類: 跑(打架) *白狗類:跑(撒嬌) */
//package check;
public class Main {
public static class Boy {
public void playWithDog(Dog dog) {
dog.run();
}
}
public static class Dog {
public void run() {
System.out.println("奔跑在綠綠的大草原!");
}
}
public static class WhiteDog extends Dog{
public void run() {
System.out.println("小白小白你真可愛!");
}
}
public static class YellowDog extends Dog{
public void run() {
System.out.println("走大黃!我們去佔地盤!嘿哈嘿哈");
}
}
public static class BlackDog extends Dog{
public void run() {
System.out.println("小黑!上啊!咬他!");
}
}
public static void main(String[] args) {
Boy boy = new Boy();
YellowDog yellowDog = new YellowDog();
BlackDog blackDog = new BlackDog();
WhiteDog whiteDog = new WhiteDog();
Dog[] dogs = {yellowDog, blackDog, whiteDog};
for (Dog dog : dogs) {
boy.playWithDog(dog);
}
}
}
運行結果 :