You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
896 B
35 lines
896 B
public class TestAnimal {
|
|
|
|
public static void animalSound(Animal a) {
|
|
a.makeSound();
|
|
}
|
|
|
|
|
|
public static void trySwim(Animal a) {
|
|
if (a instanceof Swimmable) {
|
|
Swimmable s = (Swimmable) a;
|
|
s.swim();
|
|
} else {
|
|
System.out.println("❌ 这只动物不会游泳!");
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Animal dog = new Dog();
|
|
Animal cat = new Cat();
|
|
|
|
System.out.println("=== 1. 多态调用叫声(抽象类多态) ===");
|
|
animalSound(dog);
|
|
animalSound(cat);
|
|
|
|
System.out.println("\n=== 2. 多态调用游泳(接口多态) ===");
|
|
trySwim(dog);
|
|
trySwim(cat);
|
|
|
|
|
|
System.out.println("\n=== 3. 接口引用直接调用 ===");
|
|
Swimmable swimmer = new Dog();
|
|
swimmer.swim();
|
|
}
|
|
}
|