课堂练习:教材143页4.编程题
Animal类
1 public abstract class Animal { 2 3 public abstract void cry(); 4 public abstract String getAnimalName(); 5 6 }
Simulator类
1 public class Simulator { 2 3 public void playSound(Animal animal) { 4 System.out.print(animal.getAnimalName()+":"); 5 animal.cry(); 6 } 7 }
Dog 类
public class Dog extends Animal{ public void cry() { System.out.println("汪汪汪..."); } public String getAnimalName() { return "小狗"; } }
Cat类
public class Cat extends Animal{ public void cry() { System.out.println("喵喵喵..."); } public String getAnimalName() { return "小猫"; } }
Application类
public class Application { public static void main(String[] args) { Simulator simulator=new Simulator(); simulator.playSound(new Dog()); simulator.playSound(new Cat()); } }
运行结果: