面向抽象编程

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

源程序如下:

abstract class Animal {

    abstract void cry();

    abstract String getAnimalName();

}

 class Simulator {

    void playSound(Animal animal) {

       System.out.print("现在播放"+animal.getAnimalName()+"类的声音:");

       animal.cry();

   }

}

class Dog extends Animal {

   void cry() {

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

   }  

    String getAnimalName() {

      return "";

   }

}

class Cat extends Animal {

   void cry() {

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

   }  

   String getAnimalName() {

      return "";

   }

}

class Qingwa extends Animal {

   void cry() {

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

   }  

   String getAnimalName() {

      return "青蛙";

   }

}

public class Example2_1 {

   public static void main(String args[]) {

      Simulator simulator = new Simulator();

      simulator.playSound(new Dog());

      simulator.playSound(new Cat());

      simulator.playSound(new Qingwa());

   }

}

运行结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值