4 changed files with 46 additions and 0 deletions
@ -0,0 +1,26 @@ |
|||||
|
public class AnimalTest { |
||||
|
public static void main(String[] args) { |
||||
|
// 创建动物数组,演示多态
|
||||
|
Animal[] animals = new Animal[2]; |
||||
|
animals[0] = new Dog(); |
||||
|
animals[1] = new Cat(); |
||||
|
|
||||
|
// 测试多态调用makeSound方法
|
||||
|
System.out.println("测试动物叫声:"); |
||||
|
for (Animal animal : animals) { |
||||
|
animal.makeSound(); |
||||
|
} |
||||
|
|
||||
|
// 测试Dog的swim方法
|
||||
|
System.out.println("\n测试游泳能力:"); |
||||
|
if (animals[0] instanceof Swimmable) { |
||||
|
((Swimmable) animals[0]).swim(); |
||||
|
} |
||||
|
|
||||
|
if (animals[1] instanceof Swimmable) { |
||||
|
((Swimmable) animals[1]).swim(); |
||||
|
} else { |
||||
|
System.out.println("猫不会游泳!"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,6 @@ |
|||||
|
public class Cat extends Animal { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("喵喵喵!"); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,11 @@ |
|||||
|
public class Dog extends Animal implements Swimmable { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("汪汪汪!"); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void swim() { |
||||
|
System.out.println("狗在游泳!"); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,3 @@ |
|||||
|
public interface Swimmable { |
||||
|
void swim(); |
||||
|
} |
||||
Loading…
Reference in new issue