1 changed files with 60 additions and 0 deletions
@ -0,0 +1,60 @@ |
|||
// 动物叫声系统
|
|||
|
|||
// 抽象类 Animal
|
|||
abstract class Animal { |
|||
// 抽象方法 makeSound()
|
|||
public abstract void makeSound(); |
|||
} |
|||
|
|||
// 接口 Swimmable
|
|||
interface Swimmable { |
|||
void swim(); |
|||
} |
|||
|
|||
// Dog 类继承 Animal 并实现 Swimmable 接口
|
|||
class Dog extends Animal implements Swimmable { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("Dog: Woof! Woof!"); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("Dog is swimming"); |
|||
} |
|||
} |
|||
|
|||
// Cat 类继承 Animal,但不实现 Swimmable 接口
|
|||
class Cat extends Animal { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("Cat: Meow! Meow!"); |
|||
} |
|||
} |
|||
|
|||
// 测试类
|
|||
public class W6作业 { |
|||
public static void main(String[] args) { |
|||
// 测试多态调用
|
|||
Animal animal1 = new Dog(); |
|||
Animal animal2 = new Cat(); |
|||
|
|||
System.out.println("Testing polymorphic calls:"); |
|||
animal1.makeSound(); |
|||
animal2.makeSound(); |
|||
|
|||
// 测试 Swimmable 接口
|
|||
System.out.println("\nTesting Swimmable interface:"); |
|||
if (animal1 instanceof Swimmable) { |
|||
((Swimmable) animal1).swim(); |
|||
} else { |
|||
System.out.println("Dog cannot swim"); |
|||
} |
|||
|
|||
if (animal2 instanceof Swimmable) { |
|||
((Swimmable) animal2).swim(); |
|||
} else { |
|||
System.out.println("Cat cannot swim"); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue