抬头望树 2023-05-13 17:29 采纳率: 83.3%
浏览 409

6-24 Animal-接口

已知有如下Animal抽象类和IAbility接口,请编写Animal子类Dog类与Cat类,并分别实现IAbility接口,另外再编写一个模拟器类Simulator调用IAbility接口方法,具体要求如下。

已有的Animal抽象类定义:
abstract class Animal{
private String name; //名字
private int age; //年龄

public Animal(String name, int age) {
    this.name = name;
    this.age = age;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}    

}
已有的IAbility接口定义:
interface IAbility{
void showInfo(); //输出动物信息
void cry(); //动物发出叫声
}
需要你编写的Dog子类:
实现IAbility接口

showInfo方法输出Dog的name、age,输出格式样例为:我是一只狗,我的名字是Mike,今年2岁(注意:输出结果中没有空格,逗号为英文标点符号)

cry方法输出Dog 的叫声,输出格式样例为:旺旺

需要你编写的Cat子类:
实现IAbility接口

showInfo方法输出Cat的name、age,输出格式样例为:我是一只猫,我的名字是Anna,今年4岁(注意:输出结果中没有空格,逗号为英文标点符号)

cry方法输出Cat 的叫声,输出格式样例为:喵喵

需要你编写的模拟器类Simulator:
void playSound(IAbility animal):调用实现了IAbility接口类的showInfo和cry方法,并显示传入动物的名字和年龄

已有的Main类定义:
public class Main {

public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    IAbility animal=null;
    int type=input.nextInt();
    String name=input.next();
    int age=input.nextInt();
    if (type==1)
        animal=new Dog(name,age);
    else
        animal=new Cat(name,age);
    
    Simulator sim=new Simulator();
    sim.playSound(animal);
    input.close();
}

}

/*请在这里填写你编写的Dog类、Cat类和Simulator类 */
输入样例:
(本题的评分点与输入样例无关)

第一个整数代表动物类型,1为狗类,2为猫类

1 Mike 2
输出样例:
我是一只狗,我的名字是Mike,今年2岁
旺旺
Mike
2

  • 写回答

1条回答 默认 最新

  • 阿里嘎多学长 2023-05-13 21:51
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:

    // Dog类
    class Dog extends Animal implements IAbility {
        public Dog(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void showInfo() {
            System.out.println("我是一只狗,我的名字是" + getName() + ",今年" + getAge() + "岁");
        }
    
        @Override
        public void cry() {
            System.out.println("旺旺");
        }
    }
    
    // Cat类
    class Cat extends Animal implements IAbility {
        public Cat(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void showInfo() {
            System.out.println("我是一只猫,我的名字是" + getName() + ",今年" + getAge() + "岁");
        }
    
        @Override
        public void cry() {
            System.out.println("喵喵");
        }
    }
    
    // Simulator类
    class Simulator {
        public void playSound(IAbility animal) {
            animal.showInfo();
            animal.cry();
            System.out.println(animal.getName());
            System.out.println(animal.getAge());
        }
    }
    

    思路:需要定义Dog类和Cat类并实现IAbility接口,实现showInfo方法和cry方法,分别输出对应的信息。同时定义Simulator类调用IAbility接口的方法并显示传入动物的名字和年龄。在Main类中通过输入的类型创建相应的对象,然后调用Simulator类的playSound方法。

    评论

报告相同问题?

问题事件

  • 创建了问题 5月13日