设计一个动物声音“模拟器”

本文介绍了一款动物声音模拟器的设计实现,通过定义接口Animal,实现了不同动物的声音模拟功能。模拟器支持多种动物声音播放,如狗叫声“汪汪”和猫叫声“喵喵”。采用面向接口编程的方式增强了系统的灵活性。

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

设计一个动物声音“模拟器”,希望模拟器可以模拟各种动物的叫声,要求如下:必须使用接口或者抽象类;至少模拟两种以上的动物种类;类名方法名定义友好;

 

public interface Animal {

void cry();

String getAnimalName();

}

 

public class Simulator {

Animal animal;

  void playSound(Animal animal){

  this.animal=animal;

  System.out.println("动物的种类是"+animal.getAnimalName()+"现在播放它的声音");

  animal.cry();

  }

  

}

 

public class Dog implements Animal{

public void cry(){

         System.out.println("汪汪 ");

     }

     public String getAnimalName(){

        return "狗";

    }

}

 

public class Cat implements Animal{

 public void cry(){

         System.out.println("喵喵 ");

     }

       public String getAnimalName(){

        return "猫";

    }

 

}

 

public class Application {

 

public static void main(String[] args) {

Simulator simulator=new Simulator();

simulator.playSound(new Dog());

simulator.playSound(new Cat());

}

 

}

 

运行结果如下:

动物的种类是狗现在播放它的声音

汪汪

动物的种类是猫现在播放它的声音

喵喵

 

 

 

 

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯子佳人傻了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值