多态练习题

package Ex01;

import java.util.Scanner;

/**
 * @Author:Adminstrator
 * @Date:2021-11-03
 * @Description:使用多态实现为宠物喂食  和 使用多态实现主人领养宠物并与宠物玩耍功能
 * 需求说明1、宠物饿了,主人需要为宠物喂食,使用多态实现该过程不同宠物吃的东西不一样,
 * 不同宠物吃完东西后恢复健康值不一样健康值达到100时,不需要继续喂食
 * 需求说明2、狗具有特有的接飞盘方法,企鹅具有特有的南极游泳方法。
 * 请编写测试类分别调用各种具体宠物的特有方法;使用向下转型,使用instanceof判断宠物类型
 */
public class Pet {
    String name;
    int health;
    @Override
    public String toString() {  //重写的toString()方法
        return name +"health="+ health;
    }

    void eat() {
    }
}

class Dog extends Pet {
    public Dog() {
        this.name = "狗狗";
        this.health = 80;
    }

    void skill(){  //狗狗特有技能
        System.out.println("我是狗狗,我可以接飞盘!");
    }
    void eat() {
        this.health += 3;
        if (this.health >= 100) {
            this.health = 100;
        }
    }
}

class Penguin extends Pet {
    public Penguin() {
        this.name = "企鹅";
        this.health = 80;
    }
    void skill(){  //企鹅特有技能
        System.out.println("我是企鹅,我可以在南极游泳!");
    }
    void eat() {
        this.health += 5;
        if (this.health >= 100) {
            this.health = 100;
        }
    }
}
class Master {
    void giveFood(Pet a) {
        a.eat();
    }
    public static void main(String[] args) {
        Master m = new Master();
        Pet d = new Dog();//向上转型
        Pet p = new Penguin();//向上转型
        if(d instanceof Dog)//用于判断d是否是Dog的实例
            ((Dog) d).skill() ;//向下转型,执行Dog的特有技能
        if(p instanceof Penguin)//用于判断p是否是Penguin的实例
            ((Penguin) p).skill();//向下转型,执行penguin的特有技能
        m.giveFood(d);//主人给d喂食
        m.giveFood(p);//主人给p喂食
        System.out.println(d.toString());
        System.out.println(p.toString());
    }
}

package Ex01;

import java.util.Scanner;

/**
 * @Author:Adminstrator
 * @Date:2021-11-03
 * @Description:打印商品价格
 *  需求说明:自定义类和方法,使用父类作为返回值实现打印不同类型商品价格功能
 *  父类:Goods(商品类)
 *  子类:TVs(电视类)、Foods(食品类)
 */
public class Human {
    public void printGoods(Goods s){
        System.out.println(s.name+"的价格为:"+s.price);
    }
    public static void main(String[] args) {
        Goods a=new TVs("电视机",5000);
        Goods b=new Foods("奶粉",200);
        Human h=new Human();
        h.printGoods(a);
        h.printGoods(b);
    }
}

class Goods {
    String name;
    double price;
}

class TVs extends Goods{
    public TVs( String a, double b) {
        this.name=a;
        this.price=b;
    }
}
class Foods extends Goods{
    public Foods(String a, double b) {
        this.name=a;
        this.price=b;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值