You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.5 KiB

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);
}
}