PTA-6-41 Animal抽象类和IAbility接口

文章介绍了如何在Java中创建Animal抽象类和IAbility接口的实现,包括Dog和Cat子类的定义,以及Simulator类调用IAbility接口的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

需要你编写的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方法。

题目给出已有的抽象类Animal、IAbility接口、Main类定义:

import java.util.Scanner;

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;
    }    
}
interface IAbility{
    void showInfo();  //输出动物信息
    void cry();    //动物发出叫声
}
/* 请在这里填写答案 */


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();
    }
}

        根据题目要求,我们需要创建两个 Animal 的子类(Dog、Cat)来实现接口 IAbility一个模拟器类(Simulator)。子类Dog、Cat要求使用showInfo方法来输出name与age,用Cry方法来输出叫声。模拟器类 Simulator 用于调用实现IAbility接口类的showInfo和cry方法。

代码实现如下:

//Dog 和 Cat 继承父类 Animal,实现接口 IAbility
class Dog extends Animal implements IAbility{

    public Dog(String name, int age) {
        super(name, age);
    }

    @Override
    public void showInfo() {
        System.out.println("我是一只狗,我的名字是"+super.getName()+",今年"+super.getAge()+"岁");
    }
    @Override
    public void cry() {
        System.out.println("旺旺");
    }
}

class Cat extends Animal implements IAbility{

    public Cat(String name, int age) {
        super(name, age);
    }

    @Override
    public void showInfo() {
        System.out.println("我是一只猫,我的名字是"+super.getName()+",今年"+super.getAge()+"岁");
    }

    @Override
    public void cry() {
        System.out.println("喵喵");
    }

}

class Simulator {
    void playSound(IAbility animal) {
        animal.showInfo();
        animal.cry();
    }
}

注:编写 showInfo方法时需要注意输出格式不要错误。


以上就是 PTA-6-41 Animal抽象类和IAbility接口 的全部内容了,希望能对你有所帮助!

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值