Animal()动物类,关于多态的练习

Animal()动物类,关于多态的练习

仅做自己练习总结

1.Dog和Cat两个类都有eat();表现形式猫了饭后喵喵叫,狗吃了饭后汪汪叫,模拟人喂食的这个过程;
2.多了一个动物叫鸭子,然后也要人去喂;
问题:如果再领养XXX宠物,就需要给XXX喂食,怎么办?

思路:
这样频繁修改代码,代码可扩展性、可维护性差。使用多态优化。
1.添加Animal类,增加eat方法,让Dog,Cat,Duck继承Animal;
2.重写eat方法修改feet的方法

Animal

/**
 * @author Linm
 * @title
 * @date 2021/8/16 17:43
 */
public class Animal {

    public String name;
    public Animal() {
    }
    public Animal(String name) {
        this.name = name;
    }
    public void eat() {
        System.out.println();
    }
}

Cat

/**
 * @author Linm
 * @title
 * @date 2021/8/16 17:23
 */
public class Cat extends Animal{
    public Cat(String name){
        super(name);
    }
    @Override
    public void eat() {
        System.out.println(this.name+"吃了鱼喵喵叫");
    }
}

Dog

/**
 * @author Linm
 * @title
 * @date 2021/8/16 17:27
 */
public class Dog extends Animal{
    public Dog(String name){
        super(name);
    }
    @Override
    public void eat(){
        System.out.println(this.name+"吃骨头汪汪叫");
    }
}

Duck

/**
 * @author Linm
 * @title
 * @date 2021/8/17 10:22
 */
public class Duck extends Animal {
    public Duck(String name){
        super(name);
    }
    @Override
    public void eat(){
        System.out.println(this.name+"吃了米嘎嘎叫");
    }
}

Person

/**
 * @author Linm
 * @title
 * @date 2021/8/16 17:04
 */
public class Person {
   String name;
   Person(){
   }
   Person(String name){
       this.name = name;
   }
   public void feed(Animal animal){
       System.out.print(this.name+"喂了"+animal.name+",");
       animal.eat();
   }
}

测试:

/**
 * @author Linm
 * @title
 * @date 2021/8/16 17:29
 */
public class Demo03 {
    public static void main(String[] args) {
        Animal cat =new Cat("cat");
        Animal dog = new Dog("dog");
        Animal duck = new Duck("duck");
        Person person = new Person("李雷");

        person.feed(cat);
        person.feed(dog);
        person.feed(duck);
    }
}

输出结果:

李雷喂了cat,cat吃了鱼喵喵叫
李雷喂了dog,dog吃骨头汪汪叫
李雷喂了duck,duck吃了米嘎嘎叫

Process finished with exit code 0
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值