5 changed files with 38 additions and 0 deletions
@ -0,0 +1,3 @@ |
|||
public abstract class Animal { |
|||
public abstract void makeSound(); |
|||
} |
|||
@ -0,0 +1,3 @@ |
|||
public interface Swimmable { |
|||
void swim(); |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
public class Dog extends Animal implements Swimmable { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("狗:汪汪汪"); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("狗会游泳"); |
|||
} |
|||
} |
|||
@ -0,0 +1,6 @@ |
|||
public class Cat extends Animal { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("猫:喵喵喵"); |
|||
} |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
public class TestAnimal { |
|||
public static void main(String[] args) { |
|||
Animal dog = new Dog(); |
|||
Animal cat = new Cat(); |
|||
|
|||
dog.makeSound(); |
|||
cat.makeSound(); |
|||
|
|||
// 向下转型调用游泳方法 |
|||
if (dog instanceof Swimmable) { |
|||
Swimmable swimmable = (Swimmable) dog; |
|||
swimmable.swim(); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue