commit
6214943cbc
10 changed files with 48 additions and 0 deletions
Binary file not shown.
@ -0,0 +1,3 @@ |
|||
public abstract class Animal { |
|||
public abstract void makeSound(); |
|||
} |
|||
Binary file not shown.
@ -0,0 +1,6 @@ |
|||
public class Cat extends Animal { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("Meow!"); |
|||
} |
|||
} |
|||
Binary file not shown.
@ -0,0 +1,11 @@ |
|||
public class Dog extends Animal implements Swimmable { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("Woof!"); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("Dog is swimming."); |
|||
} |
|||
} |
|||
Binary file not shown.
@ -0,0 +1,25 @@ |
|||
public class Main { |
|||
public static void main(String[] args) { |
|||
// 测试多态
|
|||
Animal animal1 = new Dog(); |
|||
Animal animal2 = new Cat(); |
|||
|
|||
System.out.println("Testing polymorphism:"); |
|||
animal1.makeSound(); // 应该输出 Woof!
|
|||
animal2.makeSound(); // 应该输出 Meow!
|
|||
|
|||
// 测试 Dog 的 swim 方法
|
|||
System.out.println("\nTesting Dog's swim method:"); |
|||
if (animal1 instanceof Swimmable) { |
|||
((Swimmable) animal1).swim(); |
|||
} |
|||
|
|||
// 测试 Cat 是否实现了 Swimmable
|
|||
System.out.println("\nTesting if Cat is Swimmable:"); |
|||
if (animal2 instanceof Swimmable) { |
|||
((Swimmable) animal2).swim(); |
|||
} else { |
|||
System.out.println("Cat is not Swimmable."); |
|||
} |
|||
} |
|||
} |
|||
Binary file not shown.
@ -0,0 +1,3 @@ |
|||
public interface Swimmable { |
|||
void swim(); |
|||
} |
|||
Loading…
Reference in new issue