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.
21 lines
955 B
21 lines
955 B
// 测试类,用于验证多态和接口的使用
|
|
public class TestAnimal {
|
|
public static void main(String[] args) {
|
|
// 使用多态创建Animal类型的引用,指向Dog和Cat对象
|
|
Animal dog = new Dog();
|
|
Animal cat = new Cat();
|
|
|
|
// 调用makeSound方法,多态会根据实际对象类型调用相应的方法
|
|
System.out.println("Testing makeSound() method:");
|
|
dog.makeSound(); // 实际调用Dog类的makeSound方法
|
|
cat.makeSound(); // 实际调用Cat类的makeSound方法
|
|
|
|
// 调用Dog对象的swim方法
|
|
System.out.println("\nTesting swim() method:");
|
|
// 需要将Animal类型的引用转换为Swimmable接口类型,然后调用swim方法
|
|
((Swimmable) dog).swim();
|
|
|
|
// 注意:Cat类没有实现Swimmable接口,所以不能调用swim方法
|
|
// ((Swimmable) cat).swim(); // 这行代码会编译错误
|
|
}
|
|
}
|