Java复习——继承作业

来源:互联网 发布:收入词典的网络词语 编辑:程序博客网 时间:2024/05/20 18:50

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();    }}
0 0
原创粉丝点击