2 changed files with 53 additions and 0 deletions
@ -0,0 +1,32 @@ |
|||
// 抽象类 Animal
|
|||
abstract class Animal { |
|||
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("狗叫:汪汪汪!"); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("狗会游泳,正在狗刨..."); |
|||
} |
|||
} |
|||
|
|||
// Cat 类继承 Animal,不实现 Swimmable
|
|||
class Cat extends Animal { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("猫叫:喵喵喵~"); |
|||
} |
|||
} |
|||
|
|||
|
|||
@ -0,0 +1,21 @@ |
|||
// 测试类
|
|||
public class AnimalTest { |
|||
public static void main(String[] args) { |
|||
// 多态调用
|
|||
Animal dog = new Dog(); |
|||
Animal cat = new Cat(); |
|||
|
|||
dog.makeSound(); |
|||
cat.makeSound(); |
|||
|
|||
// 判断 Dog 是否实现了 Swimmable 接口并调用
|
|||
if (dog instanceof Swimmable) { |
|||
((Swimmable) dog).swim(); |
|||
} |
|||
|
|||
// Cat 不能游泳
|
|||
if (!(cat instanceof Swimmable)) { |
|||
System.out.println("猫不会游泳"); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue