6 changed files with 56 additions and 0 deletions
Binary file not shown.
Binary file not shown.
@ -0,0 +1,56 @@ |
|||
// 抽象类Animal
|
|||
abstract class Animal { |
|||
// 抽象方法makesound()
|
|||
public abstract void makesound(); |
|||
} |
|||
|
|||
// 接口Swimmable
|
|||
interface Swimmable { |
|||
// 方法swim()
|
|||
void swim(); |
|||
} |
|||
|
|||
// Dog类继承Animal并实现Swimmable接口
|
|||
class Dog extends Animal implements Swimmable { |
|||
@Override |
|||
public void makesound() { |
|||
System.out.println("Dog barks: Woof! Woof!"); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("Dog is swimming"); |
|||
} |
|||
} |
|||
|
|||
// Cat类继承Animal
|
|||
class Cat extends Animal { |
|||
@Override |
|||
public void makesound() { |
|||
System.out.println("Cat meows: Meow! Meow!"); |
|||
} |
|||
} |
|||
|
|||
public class Animals { |
|||
public static void main(String[] args) { |
|||
// 多态测试
|
|||
Animal animal1 = new Dog(); |
|||
Animal animal2 = new Cat(); |
|||
|
|||
System.out.println("Testing polymorphism:"); |
|||
animal1.makesound(); |
|||
animal2.makesound(); |
|||
|
|||
// 测试Dog的swim方法
|
|||
System.out.println("\nTesting swim method:"); |
|||
if (animal1 instanceof Swimmable) { |
|||
((Swimmable) animal1).swim(); |
|||
} |
|||
|
|||
if (animal2 instanceof Swimmable) { |
|||
((Swimmable) animal2).swim(); |
|||
} else { |
|||
System.out.println("Cat cannot swim"); |
|||
} |
|||
} |
|||
} |
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading…
Reference in new issue