Java接口与实现(复习)

p160

Animal.java
public interface Animal {
    public abstract void cry();
    public abstract String getAnimalName();
}
Simulator.java
public class Simulator {
   public void playSound(Animal animal) {
       System.out.print("现在播放"+animal.getAnimalName()+"类的声音:");
       animal.cry();
   }
}
Dog.java
public class Dog implements Animal {
   public void cry() {
      System.out.println("汪汪...汪汪"); 
   }  
   public String getAnimalName() {
      return "狗";
   }
}
Cat.java
public class Cat implements Animal {
   public void cry() {
      System.out.println("喵喵...喵喵"); 
   }  
   public String getAnimalName() {
      return "猫";
   }
}
Application.java
public class Example5_13 {
   public static void main(String args[]) {
      Simulator simulator = new Simulator();
      simulator.playSound(new Dog());
      simulator.playSound(new Cat());
   }
}

展开阅读全文

没有更多推荐了,返回首页