2 changed files with 64 additions and 0 deletions
@ -0,0 +1,29 @@ |
|||||
|
abstract class Animal { |
||||
|
public abstract void makeSound(); |
||||
|
} |
||||
|
|
||||
|
interface Swimmable { |
||||
|
void swim(); |
||||
|
} |
||||
|
|
||||
|
class Dog extends Animal implements Swimmable { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("🐶 汪汪汪!(Dog叫声)"); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void swim() { |
||||
|
System.out.println("🐶 狗狗在水中快乐地游泳~"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
class Cat extends Animal { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("🐱 喵喵喵!(Cat叫声)"); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
@ -0,0 +1,35 @@ |
|||||
|
public class TestAnimal { |
||||
|
|
||||
|
public static void animalSound(Animal a) { |
||||
|
a.makeSound(); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
public static void trySwim(Animal a) { |
||||
|
if (a instanceof Swimmable) { |
||||
|
Swimmable s = (Swimmable) a; |
||||
|
s.swim(); |
||||
|
} else { |
||||
|
System.out.println("❌ 这只动物不会游泳!"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
|
||||
|
Animal dog = new Dog(); |
||||
|
Animal cat = new Cat(); |
||||
|
|
||||
|
System.out.println("=== 1. 多态调用叫声(抽象类多态) ==="); |
||||
|
animalSound(dog); |
||||
|
animalSound(cat); |
||||
|
|
||||
|
System.out.println("\n=== 2. 多态调用游泳(接口多态) ==="); |
||||
|
trySwim(dog); |
||||
|
trySwim(cat); |
||||
|
|
||||
|
|
||||
|
System.out.println("\n=== 3. 接口引用直接调用 ==="); |
||||
|
Swimmable swimmer = new Dog(); |
||||
|
swimmer.swim(); |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue