Java: Animals that speak

Each kind of animal answers the same question differently: polymorphism in its simplest form.

What to build

A program that makes animals speak.

Requirements

  • Write an abstract class Animal with a name, an abstract sound() and a method speak() returning NAME says SOUND, and subclasses Dog (Woof), Cat (Meow) and Cow (Moo).
  • For each line KIND NAME print what the animal says; for any other kind print unknown animal KIND.

Input

Line 1: n. Then n lines.

Output

n lines.

Constraints

1 ≤ n ≤ 50; kinds are lower case.

Example

Input:

3
dog Rex
cat Tom
cow Daisy

Output:

Rex says Woof
Tom says Meow
Daisy says Moo

Why it works

speak() is written once in Animal and calls sound(), which each subclass overrides, so the right sound is used whatever kind of animal the variable holds.

Examples

Example 1 · Input
3
dog Rex
cat Tom
cow Daisy
Expected output
Rex says Woof
Tom says Meow
Daisy says Moo
Example 2 · Input
1
fish Nemo
Expected output
unknown animal fish

Hints

Hint 1

abstract class Animal { abstract String sound(); } and subclasses Dog, Cat and Cow.

Hint 2

Create the right subclass for each line, then call speak() through an Animal variable.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

abstract class Animal {
    private final String name;

    Animal(String name) {
        this.name = name;
    }

    abstract String sound();

    String speak() {
        return name + " says " + sound();
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);
    }

    @Override
    String sound() {
        return "Woof";
    }
}

class Cat extends Animal {
    Cat(String name) {
        super(name);
    }

    @Override
    String sound() {
        return "Meow";
    }
}

class Cow extends Animal {
    Cow(String name) {
        super(name);
    }

    @Override
    String sound() {
        return "Moo";
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            String kind = in.next(), name = in.next();
            Animal a = switch (kind) {
                case "dog" -> new Dog(name);
                case "cat" -> new Cat(name);
                case "cow" -> new Cow(name);
                default -> null;
            };
            System.out.println(a == null ? "unknown animal " + kind : a.speak());
        }
    }
}

Lesson: Inheritance and polymorphism →