java学习笔记14-多态

多态可以理解为同一个操作在不同对象上会有不同的表现

比如在谷歌浏览器上按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()方法时,是调用各自子类的方法。而不是父类的方法。

转载于:https://www.cnblogs.com/myal/p/11076963.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值