Java多态性的例子

多态性是指统一的接口,不同的表现形式。在我们下面的例子中,有5个类。

Game类是Football、Basketball、Popolong的父类,Games类使用前面4个类。

Java根据动态绑定决定执行“更具体”的方法,即子类方法。

  1. //Game.java
  2. package cn.edu.uibe.oop;
  3. public class Game {
  4.  protected void play(){
  5.   System.out.println("play game");
  6.  }
  7. }
  8. //Football.java
  9. package cn.edu.uibe.oop;
  10. public class Football extends Game {
  11.  protected void play() {
  12.     System.out.println("play football");
  13.     super.play();
  14.  }
  15.  void f(){
  16.   play();
  17.  }
  18. }
  19. //Basketball.java
  20. package cn.edu.uibe.oop;
  21. public class Basketball extends Game{
  22.  protected void play() {
  23.   System.out.println("play basketball");
  24.  }
  25. }
  26. //Popolong.java
  27. package cn.edu.uibe.oop;
  28. public class Popolong extends Game {
  29.  protected void play() {
  30.   System.out.println("play popolong");
  31.  }
  32. }
  33. //Games.java
  34. package cn.edu.uibe.oop;
  35. public class Games {
  36.  public static void main(String[] args) {
  37.   Game[] games = new Game[10];
  38.   games[0] = new Basketball();
  39.   games[1] = new Football();
  40.   games[2] = new Popolong();
  41.   
  42.   for(int i=0;i<games.length;i++){
  43.    if(games[i]!=null)
  44.       games[i].play();
  45.   }
  46.   
  47.  }
  48. }




 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值