题目描述
按照以下提供的Main类及Dog类(Pet类的子类),及输入、输出样例
1. 编写抽象类Pet,包含构造方法, 抽象方法eat和setNameAge及成员变量:name, age,静态变量count;
2. 编写Cat类(Pet类的子类)
3. 编写TheOther类(Pet类的子类)。
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner r = new Scanner(System.in);
int count;
if( !r.hasNextInt() )
return;
count = r.nextInt();
if( count < 0 )
return;
Pet petList[] = new Pet[count];
for(int i=0;i<count;i++)
{
int category;
String name;
int age;
if( !r.hasNextInt() )
return;
category = r.nextInt();
if(category == 1)
{
petList[i] = new Dog();
}
else if(category == 2)
{
petList[i] = new Cat();
}
else
{
petList[i] = new TheOther();
}
name = r.next();
if( !r.hasNextInt() )
return;
age = r.nextInt();
if( age < 0 )
return;
petList[i].setNameAge(name, age);
petList[i].eat();
}
System.out.print("Therefore, I have "+ Pet.count +" pets, including ");
System.out.print( Dog.numOfDog +" dogs, and ");
System.out.print( Cat.numOfCat +" cats, and ");
System.out.println( TheOther.numOfTheOther +" other animals ");
}
}
class Dog extends Pet
{
static int numOfDog = 0;
public Dog()
{
numOfDog++;
}
public void setNameAge(String name, int age)
{
super.name = name;
super.age = age;
System.out.print("She/He said: \"I am a dog. ");
System.out.print("My name is "+ name+ ". ");
}
public void eat()
{
System.out.println("I like eating bone.\"");
}
}
输入
先输入pet的数量,
再依次输入 pet 的种类(1代表狗,2代表猫,否则代表其他),名字,年龄;
输出
详见样例输出。
样例输入
3 1 wangcai 2 2 Tom 3 3 Jerry 4
样例输出
She/He said: "I am a dog. My name is wangcai. I like eating bone." She/He said: "I am a cat. My name is Tom. I like eating fish." She/He said: "I don't know what i am. My name is Jerry. I like eating everything." Therefore, I have 3 pets, including 1 dogs, and 1 cats, and 1 other animals
abstract class Pet{
protected String name;
protected int age;
static int count;
public Pet() {
count++;
}
public void setNameAge(String name, int age) {
this.name = name;
this.age = age;
}
abstract public void eat();
}
class Cat extends Pet
{
static int numOfCat = 0;
public Cat()
{
numOfCat++;
}
public void setNameAge(String name, int age)
{
super.name = name;
super.age = age;
System.out.print("She/He said: \"I am a cat. ");
System.out.print("My name is "+ name+ ". ");
}
public void eat()
{
System.out.println("I like eating fish.\"");
}
}
class TheOther extends Pet
{
static int numOfTheOther = 0;
public TheOther()
{
numOfTheOther++;
}
public void setNameAge(String name, int age)
{
super.name = name;
super.age = age;
System.out.print("She/He said: \"I don't know what i am. ");
System.out.print("My name is "+ name+ ". ");
}
public void eat()
{
System.out.println("I like eating everything.\"");
}
}