2 changed files with 54 additions and 0 deletions
@ -0,0 +1,31 @@ |
|||||
|
abstract class Animal { |
||||
|
// 抽象方法:动物叫声
|
||||
|
public abstract void makeSound(); |
||||
|
} |
||||
|
|
||||
|
// 2. Swimmable 接口
|
||||
|
interface Swimmable { |
||||
|
// 游泳方法
|
||||
|
void swim(); |
||||
|
} |
||||
|
|
||||
|
// 3. Dog 类:继承 Animal,实现 Swimmable
|
||||
|
class Dog extends Animal implements Swimmable { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("小狗汪汪叫:汪汪汪!"); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void swim() { |
||||
|
System.out.println("小狗在水里狗刨式游泳!"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 4. Cat 类:继承 Animal,不实现 Swimmable
|
||||
|
class Cat extends Animal { |
||||
|
@Override |
||||
|
public void makeSound() { |
||||
|
System.out.println("小猫喵喵叫:喵喵喵!"); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,23 @@ |
|||||
|
public class AnimalTest { |
||||
|
public static void main(String[] args) { |
||||
|
// 多态方式创建对象
|
||||
|
Animal dog = new Dog(); |
||||
|
Animal cat = new Cat(); |
||||
|
|
||||
|
// 调用 makeSound 方法(多态体现)
|
||||
|
System.out.println("=== 动物叫声测试 ==="); |
||||
|
dog.makeSound(); |
||||
|
cat.makeSound(); |
||||
|
|
||||
|
// 测试 Swimable 接口(Dog 能游泳,Cat 不能)
|
||||
|
System.out.println("\n=== 游泳能力测试 ==="); |
||||
|
if (dog instanceof Swimmable) { |
||||
|
((Swimmable) dog).swim(); |
||||
|
} |
||||
|
if (cat instanceof Swimmable) { |
||||
|
((Swimmable) cat).swim(); |
||||
|
} else { |
||||
|
System.out.println("小猫不会游泳哦!"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue