2、设计一个动物声音“模拟器”,希望模拟器可以模拟各种动物的叫声,要求如下:必须使用接口或者抽象类;至少模拟两种以上的动物种类;类名方法名定义友好;
源代码如下:
interface Animal {
public abstract void cry();
public abstract String getAnimalName();
}
class Simulaor {
public void playSound(Animal animal) {
System.out.print("现在播放"+animal.getAnimalName()+"类的声音:");
animal.cry();
}
}
class Dog implements Animal {
public void cry() {
System.out.println("汪汪...汪汪");
}
public String getAnimalName() {
return "狗";
}
}
class Cat implements Animal {
public void cry() {
System.out.println("喵喵...喵喵");
}
public String getAnimalName() {
return "猫";
}
}
class text2 {
public static void main(String[] args) {
Simulaor simulator = new Simulaor();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
}
代码运行结果: