2 changed files with 55 additions and 0 deletions
@ -0,0 +1,55 @@ |
|||
// 抽象类:动物
|
|||
abstract class Animal { |
|||
// 抽象方法:动物叫声
|
|||
public abstract void makeSound(); |
|||
} |
|||
|
|||
// 接口:具备游泳能力
|
|||
interface Swimmable { |
|||
void swim(); |
|||
} |
|||
|
|||
// 狗类:继承动物,实现游泳接口
|
|||
class Dog extends Animal implements Swimmable { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("Dog: 汪汪汪"); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("Dog 正在游泳"); |
|||
} |
|||
} |
|||
|
|||
// 猫类:仅继承动物
|
|||
class Cat extends Animal { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("Cat: 喵喵喵"); |
|||
} |
|||
} |
|||
|
|||
// 测试类
|
|||
public class AnimalTest { |
|||
public static void main(String[] args) { |
|||
// 多态:父类引用指向子类对象
|
|||
Animal dog = new Dog(); |
|||
Animal cat = new Cat(); |
|||
// 测试叫声
|
|||
dog.makeSound(); |
|||
cat.makeSound(); |
|||
|
|||
// 测试游泳(仅狗实现了接口)
|
|||
if (dog instanceof Swimmable) { |
|||
((Swimmable) dog).swim(); |
|||
} else { |
|||
System.out.println("该动物不会游泳"); |
|||
} |
|||
if (cat instanceof Swimmable) { |
|||
((Swimmable) cat).swim(); |
|||
} else { |
|||
System.out.println("Cat 不会游泳"); |
|||
} |
|||
} |
|||
} |
|||
|
After Width: | Height: | Size: 206 KiB |
Loading…
Reference in new issue