设计一个动物发生模拟器,用于模拟不同 动物 的叫声。比如狮吼、虎啸、狗旺旺、猫喵喵……。 定义抽象类Animal,包含两个抽象方法:获取动物类别getAnimalClass()、动物叫shout(); 然后基于抽象类Animal定义狗类Dog
时间: 2024-05-01 09:17:43 浏览: 205
,猫类Cat,狮子类Lion和老虎类Tiger,实现它们的getAnimalClass()和shout()方法。最后,设计一个AnimalSimulator类,能够创建各种动物对象并调用它们的shout()方法进行叫声模拟。
代码示例如下:
```
// 抽象类Animal
public abstract class Animal {
// 获取动物类别
public abstract String getAnimalClass();
// 动物叫声
public abstract String shout();
}
// 狗类Dog
public class Dog extends Animal {
@Override
public String getAnimalClass() {
return "Dog";
}
@Override
public String shout() {
return "Woof! Woof!";
}
}
// 猫类Cat
public class Cat extends Animal {
@Override
public String getAnimalClass() {
return "Cat";
}
@Override
public String shout() {
return "Meow! Meow!";
}
}
// 狮子类Lion
public class Lion extends Animal {
@Override
public String getAnimalClass() {
return "Lion";
}
@Override
public String shout() {
return "Roar! Roar!";
}
}
// 老虎类Tiger
public class Tiger extends Animal {
@Override
public String getAnimalClass() {
return "Tiger";
}
@Override
public String shout() {
return "Growl! Growl!";
}
}
// 动物模拟器类AnimalSimulator
public class AnimalSimulator {
public static void main(String[] args) {
// 创建各种动物对象并调用shout()方法进行叫声模拟
Animal dog = new Dog();
Animal cat = new Cat();
Animal lion = new Lion();
Animal tiger = new Tiger();
System.out.println(dog.getAnimalClass() + ": " + dog.shout());
System.out.println(cat.getAnimalClass() + ": " + cat.shout());
System.out.println(lion.getAnimalClass() + ": " + lion.shout());
System.out.println(tiger.getAnimalClass() + ": " + tiger.shout());
}
}
```
阅读全文