abstract class Animal09 {
String name;
int age;
Animal09(String name, int age) {
this.name = name;
this.age = age;
}
abstract void makeSound();
}
class Cat extends Animal09 {
Cat(String name, int age) {
super(name, age);
}
@Override
void makeSound() {
System.out.println(name + " : 喵喵");
}
}
class Dog extends Animal09 {
Dog(String name, int age) {
super(name, age);
}
@Override
void makeSound() {
System.out.println(name + " : 汪汪");
}
}
class Rabbit extends Animal09 {
Rabbit(String name, int age) {
super(name, age);
}
@Override
void makeSound() {
System.out.println(name + " : 叽叽");
}
}
class AnimalFactory {
public Animal09 createAnimal(String type, String name, int age) {
switch (type) {
case "cat":
return new Cat(name, age);
case "dog":
return new Dog(name, age);
case "rabbit":
return new Rabbit(name, age);
default:
throw new IllegalArgumentException("Invalid animal type: " + type);
}
}
}
public class waqu {
public static void main(String[] args) {
AnimalFactory factory = new AnimalFactory();
Animal09 cat = factory.createAnimal("cat", "猫", 3);
cat.makeSound();
Animal09 dog = factory.createAnimal("dog", "犬", 5);
dog.makeSound();
Animal09 rabbit = factory.createAnimal("rabbit", "兔子", 2);
rabbit.makeSound();
}
}
题目一动物叫声
最新推荐文章于 2024-08-16 23:08:28 发布