185 - 动物体系

基于继承关系编写一个动物体系,具体的动物包含小狗和小猫。每只动物都有名字和颜色,都能够做自我介绍(introduce)。此外,小狗有智商属性(整数),能接飞盘(catchFrisbee(),方法体内输出一行“catch frisbee”即可),小猫有眼睛颜色属性,能抓老鼠(catchMouse(),方法体内输出一行“catch mouse”即可)。各种小动物自我介绍时均介绍自己的姓名和颜色,此外,小狗应介绍自己的智商,小猫应介绍自己的眼睛颜色。小狗介绍时输出”My name is xxx, my color is xxx, my IQ is xxx”, 小猫介绍时输出“My name is xxx, my color is xxx, my eyecolor is xxx”
构造类TestAnimal,提供静态函数introduce(Animal),对参数动物自我介绍。提供静态函数action(Animal),根据参数对象的实际类型进行活动,如果是小狗,则让其接飞盘,如果是小猫,则让其抓老鼠。
Main函数中,根据动物类型构造动物,并调用TestAnimal中的方法进行自我介绍(introduce)和活动(action)
abstract class Animal{
    protected String name;

    protected String color;

    public Animal(String name, String color) {

        this.name = name;

        this.color = color;

    }

    public abstract void introduce();

}

class Dog extends Animal{

    private int IQ;

    public Dog(String name,String color, int IQ) {

        super(name, color);

        this.IQ = IQ;

    }

    public void introduce() {

        System.out.println("My name is "+name+", my color is "+color+", my IQ is "+IQ);

    }

    public void catchFrisbee() {

        System.out.println("catch frisbee");

    }

}

class Cat extends Animal{

    private String eyeColor;

    public Cat(String name, String color, String eyeColor) {

        super(name, color);

        this.eyeColor = eyeColor;

    }

    public void introduce() {

        System.out.println("My name is "+name+", my color is "+color+", my eyecolor is "+eyeColor);

    }

    public void catchMouse() {

        System.out.println("catch mouse");

    }

}

class TestAnimal{

    public static void introduce(Animal a) {

        

        if(a instanceof Dog) {

            Dog dog = (Dog)a;

            dog.introduce();

        }

        else {

            Cat cat = (Cat)a;

            cat.introduce();

        }

        

    }

    public static void action(Animal a) {

        if(a instanceof Dog) {

            Dog dog = (Dog)a;

            dog.catchFrisbee();;

        }

        else {

            Cat cat = (Cat)a;

            cat.catchMouse();;

        }

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值