1 changed files with 52 additions and 0 deletions
@ -0,0 +1,52 @@ |
|||||
|
// 抽象类 Animal,包含抽象方法 makeSound()
|
||||
|
abstract class Animal { |
||||
|
public abstract void makeSound(); |
||||
|
} |
||||
|
|
||||
|
// 接口 Swimmable,包含方法 swim()
|
||||
|
interface Swimmable { |
||||
|
void swim(); |
||||
|
} |
||||
|
|
||||
|
// Dog 类继承 Animal 并实现 Swimmable 接口
|
||||
|
class Dog extends Animal implements Swimmable { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("汪汪!"); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void swim() { |
||||
|
System.out.println("狗在游泳!"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Cat 类继承 Animal,不实现 Swimmable 接口
|
||||
|
class Cat extends Animal { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("喵喵!"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 测试类,包含 main 方法用于测试多态调用
|
||||
|
public class AnimalSystem { |
||||
|
public static void main(String[] args) { |
||||
|
// 创建 Dog 和 Cat 实例
|
||||
|
Animal dog = new Dog(); |
||||
|
Animal cat = new Cat(); |
||||
|
|
||||
|
// 多态调用:通过 Animal 类型引用调用子类的 makeSound 方法
|
||||
|
dog.makeSound(); // 输出:汪汪!
|
||||
|
cat.makeSound(); // 输出:喵喵!
|
||||
|
|
||||
|
// 测试 Dog 是否可以游泳(Swimmable 接口)
|
||||
|
if (dog instanceof Swimmable) { |
||||
|
((Swimmable) dog).swim(); // 输出:狗在游泳!
|
||||
|
} |
||||
|
|
||||
|
// Cat 不实现 Swimmable,不能调用 swim() 方法
|
||||
|
// 下面这行会报错:cat 不是 Swimmable 类型
|
||||
|
// ((Swimmable) cat).swim();
|
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue