设计一个动物发声模拟器,用于模拟不同动物的叫声。比如狮吼、虎啸、狗旺旺、猫喵喵……。定义抽象类Animal,包含两个抽象方法:获取动物类别getAnimalClass()、动物叫shout();然后基于抽象类Animal定义狗类Dog、猫类Cat和山羊Goat,用getAnimalClass()方法返回不同的动物类别(比如猫,狗,山羊),用shout()方法分别输出不同的叫声(比如喵喵、汪汪、咩咩)。最后编写AnimalShoutTest类测试
时间: 2024-02-11 07:08:46 浏览: 151
好的,以下是动物发声模拟器的代码:
Animal.java
```
public abstract class Animal {
public abstract String getAnimalClass();
public abstract String shout();
}
```
Dog.java
```
public class Dog extends Animal {
@Override
public String getAnimalClass() {
return "Dog";
}
@Override
public String shout() {
return "Woof Woof!";
}
}
```
Cat.java
```
public class Cat extends Animal {
@Override
public String getAnimalClass() {
return "Cat";
}
@Override
public String shout() {
return "Meow Meow!";
}
}
```
Goat.java
```
public class Goat extends Animal {
@Override
public String getAnimalClass() {
return "Goat";
}
@Override
public String shout() {
return "Baa Baa!";
}
}
```
AnimalShoutTest.java
```
public class AnimalShoutTest {
public static void main(String[] args) {
Animal[] animals = {new Dog(), new Cat(), new Goat()};
for (Animal animal : animals) {
System.out.println(animal.getAnimalClass() + " shouts: " + animal.shout());
}
}
}
```
运行AnimalShoutTest类,输出结果如下:
```
Dog shouts: Woof Woof!
Cat shouts: Meow Meow!
Goat shouts: Baa Baa!
```
这个模拟器可以通过添加新的动物类来模拟更多种类的动物的叫声。
阅读全文