2 changed files with 80 additions and 0 deletions
@ -0,0 +1,66 @@ |
|||
public class MainSix { |
|||
public static abstract class Animal { |
|||
protected String name; |
|||
|
|||
Animal(String name) { |
|||
this.name = name; |
|||
} |
|||
|
|||
abstract public void makeSound(); |
|||
} |
|||
|
|||
public interface Swimmable { |
|||
void swim(); |
|||
} |
|||
|
|||
public static class Dog extends Animal implements Swimmable { |
|||
Dog(String name) { |
|||
super(name); |
|||
} |
|||
|
|||
@Override |
|||
public void makeSound() { |
|||
System.out.printf("This is dog %s.%n", this.name); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.printf("Dog %s swimming.%n", this.name); |
|||
} |
|||
} |
|||
|
|||
public static class Cat extends Animal { |
|||
Cat(String name) { |
|||
super(name); |
|||
} |
|||
|
|||
@Override |
|||
public void makeSound() { |
|||
System.out.printf("This is cat %s.%n", this.name); |
|||
} |
|||
} |
|||
|
|||
public static void trySwim(Animal animal) { |
|||
System.out.printf("Moving %s to swimming pool.%n", animal.name); |
|||
|
|||
if (animal instanceof Swimmable) { |
|||
((Swimmable) animal).swim(); |
|||
} else { |
|||
System.out.printf("Oops, looks like %s cannot swim...%n", animal.name); |
|||
} |
|||
} |
|||
|
|||
public static void main(String[] args) { |
|||
Animal dog1 = new Dog("Adam"); |
|||
Animal dog2 = new Dog("Belly"); |
|||
Animal cat1 = new Cat("Carl"); |
|||
|
|||
dog1.makeSound(); |
|||
dog2.makeSound(); |
|||
cat1.makeSound(); |
|||
|
|||
trySwim(dog1); |
|||
trySwim(dog2); |
|||
trySwim(cat1); |
|||
} |
|||
} |
|||
@ -0,0 +1,14 @@ |
|||
# 运行记录 |
|||
|
|||
```console |
|||
$ javac MainSix.java && java MainSix |
|||
This is dog Adam. |
|||
This is dog Belly. |
|||
This is cat Carl. |
|||
Moving Adam to swimming pool. |
|||
Dog Adam swimming. |
|||
Moving Belly to swimming pool. |
|||
Dog Belly swimming. |
|||
Moving Carl to swimming pool. |
|||
Oops, looks like Carl cannot swim... |
|||
``` |
|||
Loading…
Reference in new issue