1 changed files with 80 additions and 0 deletions
@ -0,0 +1,80 @@ |
|||||
|
// 抽象类 Animal |
||||
|
abstract class Animal { |
||||
|
protected String name; |
||||
|
|
||||
|
public Animal(String name) { |
||||
|
this.name = name; |
||||
|
} |
||||
|
|
||||
|
public abstract void makeSound(); |
||||
|
} |
||||
|
|
||||
|
// 接口 Swimmable |
||||
|
interface Swimmable { |
||||
|
void swim(); |
||||
|
} |
||||
|
|
||||
|
// Dog 类:继承 Animal,实现 Swimmable |
||||
|
class Dog extends Animal implements Swimmable { |
||||
|
public Dog(String name) { |
||||
|
super(name); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println(name + " 汪汪叫"); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void swim() { |
||||
|
System.out.println(name + " 正在游泳 "); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Cat 类:只继承 Animal,不实现 Swimmable |
||||
|
class Cat extends Animal { |
||||
|
public Cat(String name) { |
||||
|
super(name); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println(name + " 喵喵叫"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 测试主类 |
||||
|
public class AnimalTest { |
||||
|
public static void main(String[] args) { |
||||
|
// 多态测试 |
||||
|
Animal dog = new Dog("旺财"); |
||||
|
Animal cat = new Cat("咪咪"); |
||||
|
|
||||
|
System.out.println("=== 动物叫声 ==="); |
||||
|
dog.makeSound(); |
||||
|
cat.makeSound(); |
||||
|
|
||||
|
System.out.println("\n=== 游泳测试 ==="); |
||||
|
// 只有实现 Swimmable 的动物才能游泳 |
||||
|
if (dog instanceof Swimmable) { |
||||
|
((Swimmable) dog).swim(); |
||||
|
} |
||||
|
|
||||
|
if (cat instanceof Swimmable) { |
||||
|
((Swimmable) cat).swim(); |
||||
|
} else { |
||||
|
System.out.println(cat.name + " 不会游泳 "); |
||||
|
} |
||||
|
|
||||
|
System.out.println("\n=== 集合多态测试 ==="); |
||||
|
// 将所有动物放入数组 |
||||
|
Animal[] animals = {dog, cat}; |
||||
|
for (Animal animal : animals) { |
||||
|
animal.makeSound(); |
||||
|
// 检查是否会游泳 |
||||
|
if (animal instanceof Swimmable) { |
||||
|
((Swimmable) animal).swim(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue