5 changed files with 68 additions and 0 deletions
@ -0,0 +1,5 @@ |
|||||
|
// 抽象类:动物
|
||||
|
public abstract class Animal { |
||||
|
// 抽象方法:发出叫声,没有方法体
|
||||
|
public abstract void makeSound(); |
||||
|
} |
||||
@ -0,0 +1,36 @@ |
|||||
|
// 测试类:主方法
|
||||
|
public class AnimalTest { |
||||
|
public static void main(String[] args) { |
||||
|
// 1. 多态:用父类引用指向子类对象
|
||||
|
Animal dog = new Dog(); |
||||
|
Animal cat = new Cat(); |
||||
|
|
||||
|
System.out.println("=== 动物叫声测试 ==="); |
||||
|
// 多态调用:根据实际对象类型执行对应方法
|
||||
|
dog.makeSound(); // 输出:汪汪汪!
|
||||
|
cat.makeSound(); // 输出:喵喵喵!
|
||||
|
|
||||
|
System.out.println("\n=== 游泳功能测试 ==="); |
||||
|
// 2. 类型判断:只有Dog能游泳,Cat不能
|
||||
|
if (dog instanceof Swimmable) { |
||||
|
Swimmable swimmableDog = (Swimmable) dog; |
||||
|
swimmableDog.swim(); // 输出:狗在水里欢快地游泳~
|
||||
|
} |
||||
|
|
||||
|
if (cat instanceof Swimmable) { |
||||
|
// Cat 不实现 Swimmable,所以这段代码不会执行
|
||||
|
Swimmable swimmableCat = (Swimmable) cat; |
||||
|
swimmableCat.swim(); |
||||
|
} else { |
||||
|
System.out.println("猫不会游泳~"); |
||||
|
} |
||||
|
|
||||
|
System.out.println("\n=== 数组多态遍历 ==="); |
||||
|
// 3. 用数组存储多个动物,统一调用
|
||||
|
Animal[] animals = {new Dog(), new Cat()}; |
||||
|
for (Animal animal : animals) { |
||||
|
animal.makeSound(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
@ -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 { |
||||
|
// 接口方法:游泳
|
||||
|
void swim(); |
||||
|
} |
||||
Loading…
Reference in new issue