程序在运行时,若输入“马”,则输出如下下图所示结果,若输入“金鱼”,则输出如下图所示结果。
,
请根据上述代码及运行结果,完成Animal、Horse、Goldfish三个类的定义(给出完整代码)。
要求:
(1)Animal必须是一个抽象类;
(2)类的设计要尽可能体现代码的可重用性,利用好面向对象的三大特性;
(3)类的设计遵循开闭原则,即:主方法中可以创建新的动物类,如Bird类(在if和else 之间添加else if语句块即可),且增加新类型的动物对象时,只需增加代码,不需修改已有代码的内容。
(4)代码要符合常识,不能为了能产生上述结果而拼凑代码,例如:eat方法中输出“我在奔跑”等等是不允许的。
import java.util.Scanner;
public class hores {
public static Scanner sc=new Scanner(System.in);
public static void main(String[] args){
Animal animal;
String type=sc.nextLine();
if(type.equals("马")){
Horse h = new Horse("马","2010-1-9");
h.run();
animal=h;
}else{
Goldfish g = new Goldfish("金鱼","2019-10-20");
g.swim();
animal=g;
}
animal.eat();
animal.showInfo();
sc.close();
}
}
class Animal{
String name;String birthday;String food;
void eat() {
System.out.println("我在吃"+food);
}
void showInfo(){
System.out.println("我是"+name+",出生日期:"+birthday);
}
}
class Horse extends Animal{
Horse(String name,String birthday){
this.birthday=birthday;
this.name=name;
this.food="草";
}
void run(){
System.out.println("我在奔跑");
}
}
class Goldfish extends Animal{
// String food=;
Goldfish(String name,String birthday){
this.birthday=birthday;
this.name=name;
this.food="鱼吃的食物";
}
void swim(){
System.out.println("我在游泳");
}
}