Wintre vacation第四次课

Java多态练习

 

1· 创建一个Pet类

public abstract class Pet {
    private int health;
 
    public Pet(){
 
    }
 
    public Pet (int health){
        this.health = health;
    }
 
    public int getHealth(){
        return health;
    }
 
    //  判断健康值
    public void setHealth(int health) {
        this.health = health;
        if (this.health > 100){
            this.health = 100;
            System.out.println("吃不下了,要消化一下");
        }
    }
 
    //抽象
    public abstract void eat(String food);
}

2·创建狗狗和企鹅

public class Dog extends Pet{  //继承父类
 
    public Dog(int health){
        super(health);
    }
 
    @Override
    public void eat(String food) {
        System.out.println("狗狗的初始健康值:" + getHealth() + ",狗狗想吃" + food + ";狗狗吃到了" + food + ",健康值加3");
        setHealth(getHealth()+3);
    }
}

public class Penguin extends Pet{
 
    public Penguin(int health){
        super(health);
    }
 
    @Override
    public void eat(String food) {
        System.out.println("企鹅的初始健康值:" + getHealth() + ",企鹅想吃" + food + ";企鹅吃到了" + food + ",健康值加5");
        setHealth(getHealth()+5);
    }
}

3·新增小猫

public class Cat extends Pet{
 
    public Cat(int health){
        super(health);
    }
 
    @Override
    public void eat(String food) {
        System.out.println("小猫的初始健康值:" + getHealth() + ",小猫想吃" + food + ";小猫吃到了" + food + ",健康值加4");
        setHealth(getHealth()+4);
    }
}
public class Person {
 
    //吃东西
    public void feed(Pet pet,String food){
        pet.eat(food);
        String f = food;
    }
 
    public static void main(String[] args) {
        //给宠物喂食
        Person person = new Person();
        Pet dog = new Dog(82);
        person.feed(dog,"狗粮");
        System.out.println("狗狗吃完后的健康值是" + dog.getHealth());
 
        Pet penguin = new Penguin(60);
        person.feed(penguin,"鱼");
        System.out.println("企鹅吃完后的健康值是" + penguin.getHealth());
 
        Pet cat = new Cat(84);
        person.feed(cat,"鲜鱼");
        System.out.println("小猫吃完后的健康值是" + cat.getHealth());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值