多态应用

多态应用

package com.lewen.opp;

public class App {
    public void showAdd() {
        System.out.println("打广告");
    }
}
package com.lewen.opp;

public class QQ extends App {
    public void showAdd() {
        System.out.println("QQ渠道打广告");
    }
}
package com.lewen.opp;

public class WeChat extends App {
    public void showAdd() {
        System.out.println("微信渠道打广告");
    }
}

package com.lewen.opp;

public class Business {
    public void makeAdd(App app) {
        app.showAdd();
        System.out.println("广而告之");
    }
}

测试一下

package com.lewen.opp;

public class Customer {
    public static void main(String[] args) {
        Business bs = new Business();
//        QQ qq = new QQ();
//        WeChat wechat = new WeChat();
        App qq = new QQ();    // 向上转与不转都可以,
        App wechat = new WeChat();
        bs.makeAdd(qq);
        bs.makeAdd(wechat);
    }

}

结果:

QQ渠道打广告

广而告之

微信渠道打广告

广而告之

总结: 多态具有超强的可扩展性.

练习

根据以下类图来完成”游戏代练”场景
 
类图地址: https://www.processon.com/view/link/5c91ed1ae4b0f88919b54bc7
 
Game:
 
 package com.xyq.bao;
 ​
 public class Game {
 ​
     public void start(){
         System.out.println("开机, 准备战斗");
     }
     public void play(){
         System.out.println("玩儿起来啊");
     }
 ​
     public void end(){
         System.out.println("关机, 结束战斗");
     }
 }
 
 ​
DNF:
 
 package com.xyq.bao;
 ​
 public class DNF extends Game{
 ​
     public void play(){
         System.out.println("开挂, 刷图, 机械牛你别跑");
     }
 }
 
 ​
LOL:
 
 package com.xyq.bao;
 ​
 public class LOL extends Game {
     public void play(){
         System.out.println("还是盖伦牛B, 神马快乐托儿所, 都是渣渣. ");
     }
 }
 ​
CS:
 
 package com.xyq.bao;
 ​
 public class CS extends Game {
     public void play(){
         System.out.println("8倍镜没有. 还是喷子比较牛B");
     }
 }
 ​
Player:
 
 package com.xyq.bao;
 ​
 public class Player {
 ​
     public void happy(Game game){
         game.start();
         game.play();
         game.end();
     }
 }
 
 ​
Client:
 
 package com.xyq.bao;
 ​
 public class Client {
     public static void main(String[] args) {
         Player player = new Player();
         Game game1 = new DNF();
         Game game2 = new LOL();
         Game game3 = new CS();
 ​
         player.happy(game1);
         player.happy(game2);
         player.happy(game3);
     }
 }

 

posted @ 2020-01-19 15:28  前海渔文乐  阅读(157)  评论(0编辑  收藏  举报