6 changed files with 58 additions and 0 deletions
@ -0,0 +1,4 @@ |
|||
public abstract class Animal { |
|||
// 抽象方法:发出声音,子类必须重写
|
|||
public abstract void makeSound(); |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
public class AnimalTest { |
|||
public static void main(String[] args) { |
|||
System.out.println("=== 1. 多态调用Animal父类引用 ==="); |
|||
// 父类引用指向子类对象(多态核心)
|
|||
Animal dog = new Dog(); |
|||
Animal cat = new Cat(); |
|||
|
|||
// 多态调用makeSound():运行时自动执行子类的方法
|
|||
dog.makeSound(); // 输出:汪汪汪!
|
|||
cat.makeSound(); // 输出:喵喵喵!
|
|||
System.out.println("\n=== 2. 测试Dog的游泳能力(接口多态) ==="); |
|||
// 接口引用指向实现类对象(接口多态)
|
|||
Swimmable swimmableDog = new Dog(); |
|||
swimmableDog.swim(); // 输出:小狗在水里游泳~
|
|||
System.out.println("\n=== 3. 类型判断与向下转型(可选拓展) ==="); |
|||
// 判断Animal对象是否能游泳(instanceof)
|
|||
if (dog instanceof Swimmable) { |
|||
System.out.println("Dog是可游泳的"); |
|||
// 向下转型为Swimmable,调用swim方法
|
|||
((Swimmable) dog).swim(); |
|||
} |
|||
if (cat instanceof Swimmable) { |
|||
System.out.println("Cat是可游泳的"); |
|||
} else { |
|||
System.out.println("Cat不会游泳"); |
|||
} |
|||
} |
|||
} |
|||
|
After Width: | Height: | Size: 320 KiB |
@ -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("汪汪汪!"); |
|||
} |
|||
|
|||
// 实现接口的swim方法
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("小狗在水里游泳~"); |
|||
} |
|||
} |
|||
@ -0,0 +1,4 @@ |
|||
public interface Swimmable { |
|||
// 抽象方法:游泳
|
|||
void swim(); |
|||
} |
|||
Loading…
Reference in new issue