多态可以理解为同一个操作在不同对象上会有不同的表现
比如在谷歌浏览器上按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()方法时,是调用各自子类的方法。而不是父类的方法。