设计一个动物声音“模拟器”,希望模拟器可以模拟许多动物的叫声。要求如下:
(1)编写抽象类Animal
Animal抽象类有2个抽象方法cry()和getAnimaName(),即要求各种具体的动物给出自己的叫声和种类名称。
(2)编写模拟器类Simulator
该类有一个playSound(Animal animal)方法,该方法的参数是Animal类型。即参数animal可以调用Animal的子类重写的cry()方法播放具体动物的声音、调用子类重写的getAnimalName()方法显示动物种类的名称。
(3)编写Animal类的子类:Dog,Cat类
(4)编写主类Application(用户程序)
在主类Application的main方法中至少包含如下代码:
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
(1)思路
定义抽象类Animal封装两个方法cry和getAnimaName,然后定义两个子类Dog类和Cat类继承Animal类,分别重写cry和getAnimaName方法,然后在Simulator中利用上转型对象来实现对子类重写的方法调用,即利用playSound(Animal animal)方法,在测试类中参数为new Dog()或new Cat()就相当于上转型对象了。最后在测试类中调试即可。
(2)代码实现
package 实验;
abstract class Animal{
abstract void cry();
abstract void getAnimaName();
}
class Dog extends Animal{
void cry() {
System.out.println("汪汪");
}
void getAnimaName() {
System.out.println("狗狗");
}
}
class Cat extends Animal{
void cry() {
System.out.println("喵喵");
}
void getAnimaName() {
System.out.println("猫猫");
}
}
class Simulator{
void playSound(Animal animal) {
animal.cry();
animal.getAnimaName();
}
}
class Ab{
public static void main(String args[]) {
Simulator simulator=new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
}
(3)运行结果截图

这个示例展示了如何使用Java编程语言设计一个动物声音模拟器。通过定义一个抽象类Animal,包含抽象方法cry()和getAnimaName(),然后创建Dog和Cat子类来重写这些方法,实现了不同动物的叫声模拟。Simulator类接收Animal类型的参数并调用其cry()和getAnimaName()方法,展示多态特性。在主类Application中,通过Simulator实例播放Dog和Cat的声音。

5359

被折叠的 条评论
为什么被折叠?



