基于继承关系编写一个动物体系,具体的动物包含小狗和小猫。每只动物都有名字和颜色,都能够做自我介绍(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();;
}
}
}