6-50 动物自我介绍分数 10
基于继承关系编写一个动物体系,具体的动物包含小狗和小猫。每只动物都有名字和颜色,都能够做自我介绍(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)
函数接口定义:
public void introduce(); //自我介绍
public void action(); //动物的活动
裁判测试程序样例:
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 猫名称 猫颜色 猫眼睛颜色
2 狗名称 狗颜色 狗的智商
输出描述:
自我介绍
活动
输入样例:
1 Mikey white blue
输出样例:
My name is Mikey, my color is white, my eyecolor is blue
catch mouse
以下是答案
import java.util.Scanner;
public class Pta_6_50_2 {
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);
}
}
//以下是答案
//构造抽象类
abstract class Animal{
Animal Cat;
Animal Dog;
public String name; //好像抽象类定义中至少用protected
public String color;
Animal(String name,String color){
this.name = name;
this.color = color;
}
public abstract void introduce();
public abstract void action();
}
class Dog extends Animal{
private int IQ;
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 action() {
System.out.println("catch frisbee");
}
}
class Cat extends Animal{
private String eyescolor;
Cat(String name,String color,String eyescolor){
super(name,color);
this.eyescolor = eyescolor;
}
public void introduce() {
System.out.println("My name is " + name + ", my color is " + color + ", my eyecolor is " + eyescolor);
}
public void action() {
System.out.println("catch mouse");
}
}
class TestAnimal {
public static void introduce(Animal a) {
a.introduce();
}
public static void action(Animal a) {
a.action();
}
}