多态可以了解為同一個操作在不同對象上會有不同的表現
比如在谷歌浏覽器上按F1會彈出谷歌的幫助頁面。在windows桌面按F1會彈出windows的幫助頁面。
多态存在的三個必要條件:
繼承
重寫
父類的引用指向子類的對象
還是以之前Player類為例
public class Player {
public int number; //号碼
public int score; //得分
public String position; //司職
public String name; //姓名
public Player(String club){
System.out.println("俱樂部名稱:"+club);
}
public void playBall(){
System.out.println("姓名:"+this.name);
System.out.println("号碼:"+this.number);
System.out.println("得分:"+this.score);
System.out.println("司職:"+this.position);
}
public static void main(String[] args){
Player p1 = new FootBallPlayer();
p1.name = "齊達内";
p1.playBall();
Player p2 = new BasketBallPlayer();
p2.name = "喬丹";
p2.playBall();
}
}
public class FootBallPlayer extends Player {
public FootBallPlayer(){
super("足球俱樂部");
System.out.println("我是FootBallPlayer");
}
public void playBall(){
System.out.println("我是一名足球運動員,我的名字叫"+this.name+",娛樂不能考手");
}
}
public class BasketBallPlayer extends Player{
public BasketBallPlayer(){
super("籃球俱樂部");
System.out.println("我是BasketBallPlayer");
}
public void playBall(){
System.out.println("我是一名籃球運動員,我叫"+this.name+",我從來不上腳");
}
public void helloPlayer(){
System.out.println("Hello"+this.name);
super.playBall();
System.out.println("你好"+this.name);
}
}
可以看到通過父類的變量p1,p2來接收兩個子類的對象,這兩個對象調用playBall()方法時,是調用各自子類的方法。而不是父類的方法。