基于继承关系编写一个动物体系,具体的动物包含小狗和小猫。每只动物都有名字和颜色,都能够做自我介绍(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
参考
import java.util.Scanner;
class TestAnimal{
public static void introduce(Animal a) {
if(a instanceof Cat) {//判断强制转换才能调用子类里的方法
Cat C=(Cat)a;
System.out.println("My name is "+C.getName()+", my color is "+C.getBcolor()+", my eyecolor is "+C.getEcolor());
}else if(a instanceof Dog) {
Dog C=(Dog)a;
System.out.println("My name is "+C.getName()+", my color is "+C.getcolor()+", my IQ is "+C.getIQ());
}
}
public static void action(Animal a) {
if(a instanceof Cat) {
System.out.println("catch mouse");
}else if(a instanceof Dog) {
System.out.println("catch frisbee");
}
}
}
class Animal{
//没想到吧这里居然还能是空的
}
class Cat extends Animal{
String name;
String bcolor;
String ecolor;
public Cat(String name,String bcolor,String ecolor) {
this.bcolor=bcolor;
this.name=name;
this.ecolor=ecolor;
}
public String getName() {
return name;
}
public String getBcolor() {
return bcolor;
}
public String getEcolor() {
return ecolor;
}
}
class Dog extends Animal{
String name;
String color;
int IQ;
public Dog(String name,String color,int IQ) {
this.name=name;
this.color=color;
this.IQ=IQ;
}
public String getName() {//用来把值运出去
return name;
}
public String getcolor() {
return color;
}
public int getIQ() {
return IQ;
}
}