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.
36 lines
1.1 KiB
36 lines
1.1 KiB
package com.rental.animal;
|
|
|
|
public class AnimalTest {
|
|
public static void main(String[] args) {
|
|
System.out.println("===== 多态测试 =====\n");
|
|
|
|
Animal dog = new Dog("旺财");
|
|
Animal cat = new Cat("小白");
|
|
|
|
System.out.println("测试 makeSound 方法(多态调用):");
|
|
dog.makeSound();
|
|
cat.makeSound();
|
|
|
|
System.out.println("\n===== 测试游泳能力 =====\n");
|
|
|
|
if (dog instanceof Swimmable) {
|
|
((Swimmable) dog).swim();
|
|
}
|
|
|
|
if (cat instanceof Swimmable) {
|
|
((Swimmable) cat).swim();
|
|
} else {
|
|
System.out.println(cat.getName() + "不会游泳");
|
|
}
|
|
|
|
System.out.println("\n===== 动物数组测试 =====\n");
|
|
|
|
Animal[] animals = {new Dog("大黄"), new Cat("小花"), new Dog("黑子")};
|
|
for (Animal animal : animals) {
|
|
animal.makeSound();
|
|
if (animal instanceof Swimmable) {
|
|
((Swimmable) animal).swim();
|
|
}
|
|
}
|
|
}
|
|
}
|