设计一个动物声音“模拟器”,希望模拟器可以模拟各种动物的叫声,要求如下:必须使用接口或者抽象类;至少模拟两种以上的动物种类;类名方法名定义友好;
源程序如下:
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());
}
}
运行结果如下: