5 changed files with 84 additions and 0 deletions
@ -0,0 +1,16 @@ |
|||
// Animal.java
|
|||
public abstract class Animal { |
|||
private String name; |
|||
|
|||
public Animal(String name) { |
|||
this.name = name; |
|||
} |
|||
|
|||
// 获取名字的方法
|
|||
public String getName() { |
|||
return name; |
|||
} |
|||
|
|||
// 抽象方法:发出叫声,强制子类实现
|
|||
public abstract void makeSound(); |
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
// Cat.java
|
|||
public class Cat extends Animal { |
|||
|
|||
public Cat(String name) { |
|||
super(name); |
|||
} |
|||
|
|||
// 实现父类的抽象方法
|
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println(this.getName() + ":喵喵喵!"); |
|||
} |
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
// Dog.java
|
|||
public class Dog extends Animal implements Swimmable { |
|||
|
|||
public Dog(String name) { |
|||
super(name); // 调用父类构造器
|
|||
} |
|||
|
|||
// 实现父类的抽象方法
|
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println(this.getName() + ":汪汪汪!"); |
|||
} |
|||
|
|||
// 实现接口的游泳方法
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println(this.getName() + " 正在狗刨式游泳..."); |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
// AnimalTest.java
|
|||
public class Main { |
|||
public static void main(String[] args) { |
|||
// 1. 创建对象
|
|||
// 使用多态:父类引用指向子类对象
|
|||
Animal dog = new Dog("旺财"); |
|||
Animal cat = new Cat("咪咪"); |
|||
|
|||
System.out.println("--- 基础叫声测试 ---"); |
|||
// 2. 调用叫声方法(多态体现)
|
|||
dog.makeSound(); |
|||
cat.makeSound(); |
|||
|
|||
System.out.println("\n--- 游泳能力测试 ---"); |
|||
|
|||
// 3. 游泳测试
|
|||
// 狗会游泳:需要向下转型(或者直接判断)
|
|||
if (dog instanceof Swimmable) { |
|||
Swimmable swimmingDog = (Swimmable) dog; |
|||
swimmingDog.swim(); |
|||
} else { |
|||
System.out.println(dog.getName() + " 不会游泳"); |
|||
} |
|||
|
|||
// 猫不会游泳
|
|||
if (cat instanceof Swimmable) { |
|||
Swimmable swimmingCat = (Swimmable) cat; |
|||
swimmingCat.swim(); |
|||
} else { |
|||
System.out.println(cat.getName() + " 不会游泳"); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,3 @@ |
|||
public interface Swimmable { |
|||
void swim(); |
|||
} |
|||
Loading…
Reference in new issue