首页 > 代码库 > 作业-继承5

作业-继承5

编写一个Animal类,具有属性:种类;具有功能:吃、睡。定义其子类Fish

和Dog,定义主类E,在其main方法中分别创建其对象并测试对象的特性。

package T092205;public class Animal {    private String zhonglei;    public String getZhonglei() {        return zhonglei;    }    public void setZhonglei(String zhonglei) {        this.zhonglei = zhonglei;    }    public void eat(){        System.out.println("我需要觅食!");    }    public void sleep(){        System.out.println("我需要睡觉!");    }    public void getInfo(){        System.out.println(" 我的种类是:"+getZhonglei());    }}package T092205;public class Fish extends Animal {    public void speak(){        System.out.println("我是"+getZhonglei());    }    public void eat(){        System.out.println("我吃小鱼");    }}package T092205;public class Dog extends Animal {    public void speak(){        System.out.println("我是"+getZhonglei());    }    public void eat(){        System.out.println("我吃狗粮");    }}package T092205;public class E {    public static void main(String[] args) {        Fish a=new Fish();        a.setZhonglei("鱼");        a.getInfo();        a.eat();        a.sleep();        if(a instanceof Fish){            Fish f=(Fish)a;            f.setZhonglei("鱼");            f.eat();            f.getInfo();        }        else{            System.out.println("类型不符!");        }        Dog d = new Dog();        d.setZhonglei("狗");        d.getInfo();        Animal aa=(Dog)d;        aa.eat();        aa.sleep();    }}

技术分享

作业-继承5