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.
31 lines
1.0 KiB
31 lines
1.0 KiB
/**
|
|
* 主测试类,验证多态调用
|
|
*/
|
|
public class AnimalTest {
|
|
public static void main(String[] args) {
|
|
// 1. 多态:父类引用指向子类对象
|
|
Animal dog = new Dog();
|
|
Animal cat = new Cat();
|
|
// 2. 调用makeSound方法,体现多态
|
|
System.out.println("=== 动物叫声测试 ===");
|
|
dog.makeSound();
|
|
cat.makeSound();
|
|
// 3. 测试游泳接口:Dog实现了Swimmable,Cat未实现
|
|
System.out.println("\n=== 游泳能力测试 ===");
|
|
if (dog instanceof Swimmable) {
|
|
((Swimmable) dog).swim();
|
|
} else {
|
|
System.out.println("这只动物不会游泳");
|
|
}
|
|
if (cat instanceof Swimmable) {
|
|
((Swimmable) cat).swim();
|
|
} else {
|
|
System.out.println("猫不会游泳");
|
|
}
|
|
// 4. 直接创建Dog对象测试
|
|
System.out.println("\n=== 直接调用Dog方法 ===");
|
|
Dog myDog = new Dog();
|
|
myDog.makeSound();
|
|
myDog.swim();
|
|
}
|
|
}
|