6-2 动物体系 (25 分)
基于继承关系编写一个动物体系,具体的动物包含小狗和小猫。每只动物都有名字和颜色,都能够做自我介绍(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)
输入描述:
动物类型 动物名称 动物颜色 动物其他属性 如 1 猫名称 猫颜色 猫眼睛颜色 2 狗名称 狗颜色 狗的智商
输出描述:
自我介绍 活动
裁判测试程序样例:
import java.util.Scanner;
/*你的代码被嵌在这里 */
public class Main{
public static void main(String args[]) {
Scanner s = new Scanner (System.in);
int i = s.nextInt();
Animal a = null;
if (i==1) {
a = new Cat(s.next(), s.next(), s.next());
} else if (i==2) {
a = new Dog(s.next(), s.next(), s.nextInt());
}
TestAnimal.introduce(a);
TestAnimal.action(a);
}
}
输入样例:
在这里给出一组输入。例如:
1 Mikey white blue
输出样例:
在这里给出相应的输出。例如:
My name is Mikey, my color is white, my eyecolor is blue catch mouse
代码
/*你的代码被嵌在这里 */
class Animal {
public String name;
public String color;
public Animal(String name, String color) {
super();
this.name = name;
this.color = color;
}
public void introduce() {
}
}
class Cat extends Animal {
public String eyeColor;
public Cat(String name, String color, String eyeColor) {
super(name, color);
this.eyeColor = eyeColor;
}
public void introduce() {
System.out.printf("My name is %s, my color is %s, my eyecolor is %s\n", this.name, this.color, this.eyeColor);
}
public void catchMouse() {
System.out.println("catch mouse");
}
}
class Dog extends Animal {
public int IQ;
public Dog(String name, String color, int iQ) {
super(name, color);
IQ = iQ;
}
public void catchFrisbee() {
System.out.println("catch frisbee");
}
public void introduce() {
System.out.printf("My name is %s, my color is %s, my IQ is %d\n", this.name, this.color, this.IQ);
}
}
class TestAnimal {
public static void introduce(Animal a) {
if (a instanceof Dog) {
Dog d = (Dog) a;
d.introduce();
} else if (a instanceof Cat) {
Cat c = (Cat) a;
c.introduce();
}
}
public static void action(Animal a) {
if (a instanceof Dog) {
Dog d = (Dog) a;
d.catchFrisbee();
} else if (a instanceof Cat) {
Cat c = (Cat) a;
c.catchMouse();
}
}
}