面向抽象编程

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

源程序如下:

abstract class Animal {

    abstract void cry();

    abstract String getAnimalName();

}

 class Simulator {

    void playSound(Animal animal) {

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

       animal.cry();

   }

扫描二维码关注公众号,回复: 2186541 查看本文章

}

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

   }

}

运行结果如下:


猜你喜欢

转载自blog.csdn.net/qq_38855717/article/details/80935485