Java复习——继承作业

1.设计一个宠物商店的宠物管理
(1)创建一个宠物类(昵称、价格、种类)并派生各种宠物,每种宠物都有各自吃食的方法。
(2)创建一个商店类,可以根据种类显示该种所有的宠物信息。

import java.util.Arrays;

public class HomeWork1 {
     public static void main(String[] args){
         Dog d1 = new Dog("小白", 2000.0f, "狗");
         Dog d2 = new Dog("小黑", 1000.0f, "狗");
         Dog d3 = new Dog("小黄", 800.0f, "狗");
         Cat c1 = new Cat("汤姆", 200.0f, "猫");
         Cat c2 = new Cat("咪咪", 1200.0f, "猫");

         PetShop ps = new PetShop();
         ps.add(d1);
         ps.add(d2);
         ps.add(d3);
         ps.add(c1);
         ps.add(c2);
         for(Pet p: ps.getPets()){
             System.out.println(p.getInfo());
             p.eat();
         }
         System.out.println("-------------查找狗------------");
         Pet[] pets = ps.findBytype("狗");
         for(Pet p: pets){
             System.out.println(p.getInfo());
             p.eat();
         }
     }
}

/*
 * 宠物类
 */

class Pet{
    String name;//昵称
    float price;//价格
    String type;//种类

    public Pet(String name, float price, String type){
        this.name = name;
        this.price = price;
        this.type = type;
    }
    //吃食方法
    public void eat(){
        System.out.println(type + "吃饭了!");
    }
    //宠物信息
    public String getInfo(){
        return "我是一只" + type + ",小伙伴们都叫我" + name + ",喜欢我就把我带走吧,只需" + price + "RMB。";
    }
}

//狗类
class Dog extends Pet{
    public Dog(String name, float price, String type){
        super(name, price, type);
    }
    //吃食方法
    public void eat(){
        System.out.println("我喜欢啃大棒骨");
    }
}

//猫类
class Cat extends Pet{
    public Cat(String name, float price, String type){
        super(name, price, type);
    }
    //吃食方法
    public void eat(){
        System.out.println("我喜欢吃鱼");
    }
}

//宠物商店
class PetShop{
    private Pet[] pets = new Pet[3];
    private int count;//记数器

    //添加
    public void add(Pet p){
        if(count >= pets.length){
            int newlen = (pets.length * 3) / 2 + 1;
            pets = Arrays.copyOf(pets, newlen);
        }
        pets[count] = p;
        count++;
    }

    //获取所有宠物
    public Pet[] getPets(){
        Pet[] p = new Pet[count];
        for(int i = 0; i < pets.length; ++i){
            p[i] = pets[i];
        }
        return pets;
    }

    //根据宠物种类查找宠物信息
    public Pet[] findBytype(String type){
        PetShop ps = new PetShop();
        for(int i = 0; i < count; ++i){
            if(pets[i].type.equals(type)){
                ps.add(pets[i]);
            }
        }
        return ps.getPets();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值