8 changed files with 57 additions and 0 deletions
Binary file not shown.
@ -0,0 +1,5 @@ |
|||
// 抽象类:动物,定义所有动物的通用行为
|
|||
public abstract class Animal { |
|||
// 抽象方法:发出声音,没有方法体,由子类实现
|
|||
public abstract void makeSound(); |
|||
} |
|||
Binary file not shown.
@ -0,0 +1,25 @@ |
|||
// 测试类:主程序入口,测试多态调用
|
|||
public class AnimalTest { |
|||
public static void main(String[] args) { |
|||
// 多态:父类引用指向子类对象
|
|||
Animal dog = new Dog(); |
|||
Animal cat = new Cat(); |
|||
|
|||
// 1. 测试动物叫声的多态调用
|
|||
System.out.println("=== 动物叫声测试 ==="); |
|||
dog.makeSound(); // 执行Dog类的makeSound()
|
|||
cat.makeSound(); // 执行Cat类的makeSound()
|
|||
|
|||
// 2. 测试游泳能力(只有Dog实现了Swimmable)
|
|||
System.out.println("\n=== 游泳能力测试 ==="); |
|||
// 判断dog是否实现了Swimmable接口,避免转型异常
|
|||
if (dog instanceof Swimmable) { |
|||
Swimmable swimmableDog = (Swimmable) dog; |
|||
swimmableDog.swim(); // 执行Dog类的swim()
|
|||
} |
|||
// Cat没有实现接口,无法调用swim()
|
|||
if (!(cat instanceof Swimmable)) { |
|||
System.out.println("猫不会游泳"); |
|||
} |
|||
} |
|||
} |
|||
Binary file not shown.
@ -0,0 +1,8 @@ |
|||
// 猫类:仅继承动物抽象类,不实现游泳接口
|
|||
public class Cat extends Animal { |
|||
// 重写抽象方法:猫的叫声
|
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("喵喵喵~"); |
|||
} |
|||
} |
|||
@ -0,0 +1,14 @@ |
|||
// 狗类:继承动物抽象类,同时实现游泳接口
|
|||
public class Dog extends Animal implements Swimmable { |
|||
// 重写抽象方法:狗的叫声
|
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("汪汪汪!"); |
|||
} |
|||
|
|||
// 实现接口方法:狗会游泳
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("狗刨式游泳"); |
|||
} |
|||
} |
|||
@ -0,0 +1,5 @@ |
|||
// 接口:可游泳的,定义游泳能力
|
|||
public interface Swimmable { |
|||
// 接口方法:游泳,默认public abstract,可省略
|
|||
void swim(); |
|||
} |
|||
Loading…
Reference in new issue