Xingzhimeng 2 days ago
parent
commit
208386cf60
  1. BIN
      w6/Animal.class
  2. 5
      w6/Animal.java
  3. BIN
      w6/AnimalTest.class
  4. 25
      w6/AnimalTest.java
  5. BIN
      w6/Cat.class
  6. 8
      w6/Cat.java
  7. 14
      w6/Dog.java
  8. 5
      w6/Swimmable.java

BIN
w6/Animal.class

Binary file not shown.

5
w6/Animal.java

@ -0,0 +1,5 @@
// 抽象类:动物,定义所有动物的通用行为
public abstract class Animal {
// 抽象方法:发出声音,没有方法体,由子类实现
public abstract void makeSound();
}

BIN
w6/AnimalTest.class

Binary file not shown.

25
w6/AnimalTest.java

@ -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("猫不会游泳");
}
}
}

BIN
w6/Cat.class

Binary file not shown.

8
w6/Cat.java

@ -0,0 +1,8 @@
// 猫类:仅继承动物抽象类,不实现游泳接口
public class Cat extends Animal {
// 重写抽象方法:猫的叫声
@Override
public void makeSound() {
System.out.println("喵喵喵~");
}
}

14
w6/Dog.java

@ -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("狗刨式游泳");
}
}

5
w6/Swimmable.java

@ -0,0 +1,5 @@
// 接口:可游泳的,定义游泳能力
public interface Swimmable {
// 接口方法:游泳,默认public abstract,可省略
void swim();
}
Loading…
Cancel
Save