Animal.java
package chapter6;
public interface Animal {
void cry();
String getAnimalName();
}
Simulator.java
package chapter6;
public class Simulator{
public void playSound(Animal animal){
animal.cry();
String animalNmae = animal.getAnimalName();
System.out.println(animalNmae+"在叫");
System.out.println();
}
}
Dog.java
package chapter6;
public class Dog implements Animal {
@Override
public void cry() {
System.out.println("狗叫");
}
@Override
public String getAnimalName() {
return "狗";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
Cat.java
package chapter6;
public class Cat implements Animal {
@Override
public void cry() {
System.out.println("猫叫");
}
@Override
public String getAnimalName() {
return "猫";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
Application.java
package chapter6;
public class Application {
public static void main(String[] args) {
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
}