Java多態性的例子

來源:互聯網
上載者:User

多態性是指統一的介面,不同的表現形式。在我們下面的例子中,有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. }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.