多态性是指统一的接口,不同的表现形式。在我们下面的例子中,有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();
- }
- }
- }