Each kind of animal answers the same question in its own way: polymorphism in its simplest form.
What to build
A program that makes animals speak.
Requirements
- Write an abstract class
Animalwith a name, an abstractsound()and a methodspeak()that returnsNAME says SOUND. Subclasses:Dog(Woof),Cat(Meow) andCow(Moo). - For each line
KIND NAMEprint what the animal says. For any other kind printunknown animal KIND.
Input
Line 1: n. Then n lines kind name.
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 for every kind.
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 public function sound(): string; } and the subclasses Dog, Cat and Cow.
Hint 2
speak() is written once in Animal and calls sound().
Solution
Show one correct solution (try it yourself first)
<?php
abstract class Animal
{
public function __construct(protected string $name)
{
}
abstract public function sound(): string;
public function speak(): string
{
return $this->name . " says " . $this->sound();
}
}
class Dog extends Animal
{
public function sound(): string
{
return "Woof";
}
}
class Cat extends Animal
{
public function sound(): string
{
return "Meow";
}
}
class Cow extends Animal
{
public function sound(): string
{
return "Moo";
}
}
$n = (int) trim(fgets(STDIN));
for ($i = 0; $i < $n; $i++) {
[$kind, $name] = explode(" ", trim(fgets(STDIN)));
$animal = match ($kind) {
"dog" => new Dog($name),
"cat" => new Cat($name),
"cow" => new Cow($name),
default => null,
};
echo $animal === null ? "unknown animal $kind" : $animal->speak(), "\n";
}