public abstract class Animal {
public abstract void cry();
public abstract String getAnimalName();
}
public class Cat extends Animal {
@Override
public void cry() {
System.out.println("喵喵喵!");
}
@Override
public String getAnimalName() {
return "小猫";
}
}
public class Dog extends Animal {
@Override
public void cry() {
System.out.println("汪汪汪!");
}
@Override
public String getAnimalName() {
return "小狗";
}
}
public class Simulator {
public void palySound(Animal animal){
if(animal instanceof Dog){
System.out.println("现在是"+animal.getAnimalName()+"的叫声!");
animal.cry();
}
else if(animal instanceof Cat){
System.out.println("现在是"+animal.getAnimalName()+"的叫声!");
animal.cry();
}
}
}
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Simulator simulator = new Simulator();
System.out.println("请输入您要听的动物声音。输入1=狗狗叫声;输入2==猫猫叫声");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
switch (x) {
case 1:
simulator.palySound(new Dog());
break;
case 2:
simulator.palySound(new Cat());
break;
default:
break;
}
}
}