多態性是指統一的介面,不同的表現形式。在我們下面的例子中,有5個類。
Game類是Football、Basketball、Popolong的父類,Games類使用前面4個類。
Java根據動態綁定決定執行“更具體”的方法,即子類方法。
- //Game.java
- package cn.edu.uibe.oop;
- public class Game {
- protected void play(){
- System.out.println("play game");
- }
- }
- //Football.java
- package cn.edu.uibe.oop;
- public class Football extends Game {
- protected void play() {
- System.out.println("play football");
- super.play();
- }
- void f(){
- play();
- }
- }
- //Basketball.java
- package cn.edu.uibe.oop;
- public class Basketball extends Game{
- protected void play() {
- System.out.println("play basketball");
- }
- }
- //Popolong.java
- package cn.edu.uibe.oop;
- public class Popolong extends Game {
- protected void play() {
- System.out.println("play popolong");
- }
- }
- //Games.java
- package cn.edu.uibe.oop;
- public class Games {
- public static void main(String[] args) {
- Game[] games = new Game[10];
- games[0] = new Basketball();
- games[1] = new Football();
- games[2] = new Popolong();
-
- for(int i=0;i<games.length;i++){
- if(games[i]!=null)
- games[i].play();
- }
-
- }
- }