简单例子实现多态

多态的概念

多态即同一行为在不同的对象上会产生不同的形态,比如做同一道题,在不同的人身上就有不同的做法
多态是一种思想,要理解多态首先要理解继承,重写,向上转型,动态绑定

这里我先举个例子

我先创建一个父类对象Animal,

package Animal;

public class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat(){
        System.out.println(this.name+"正在吃东西");
    }
    public void act(){
        System.out.println(this.name+"正在行动");
    }
}

然后创建两个子类dog和bird分别继承Animal,并重写父类的两个方法

package Animal;

public class dog extends Animal{

    public dog(String name) {
        super(name);
    }
    public void eat(){
        System.out.println(this.name+"在吃骨头");
    }
    public void act(){
        System.out.println(this.name+"在地上跑");
    }
}
public class Bird extends Animal{
    public Bird(String name) {
        super(name);
    }
    public void eat(){
        System.out.println(this.name+"在吃米粒");
    }
    public void act(){
        System.out.println(this.name+"在空中飞");
    }
}

实例化两个对象,这里我使用了向上转型,然后通过父类引用调用子类和父类重写的两个方法

package Animal;

public class Test {
    public static void main(String[] args) {
        Animal animal1=new dog("小狗");
        Animal animal2=new Bird("小鸟");
        animal1.eat();
        animal2.eat();
        animal1.act();
        animal2.act();
    }
}

运行结果

所以很明显,同样是eat方法,在不同的对象上表现却不同 ,在dog对象上是吃骨头,在bird上是吃米粒,另一个act方法同理

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值