• 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. }




     

  • 相关阅读:
    JZOJ_5838. 【广州市选2011一试】旅游路线 (Standard IO)
    JZOJ_4421. aplusb (Standard IO)
    JZOJ_3928. 射击 (Standard IO)
    JZOJ_3927. 可见点数 (Standard IO)
    AFO
    基础数论Ⅱ——笑容渐渐消失
    基础数论Ⅰ——数学渣默默流泪
    模板——二分
    模板——最小费用流
    模板——Dinic
  • 原文地址:https://www.cnblogs.com/zhangyunlin/p/6168133.html
Copyright © 2020-2023  润新知