Challenge: Animal Sounds
Completed
Write a class Animal with a method String sound() that returns ..., and child classes Dog (Woof), Cat (Meow) and Cow (Moo) that override it.
Read n and then n animal names. For each, create the right object (any other name gives a plain Animal) and print <name>: <sound>.
Input
First n, then n words.
Output
One line per animal, e.g. dog: Woof.
Example
Input
3 dog cat cow
Output
dog: Woof cat: Meow cow: Moo
Editor
Java
Hints
Store every object in a variable of type Animal.
Calling a.sound() runs the version of the real object.
Solution explanation
The variable has the parent type, but Java calls each child's overridden sound() – that's polymorphism.
Show solution
import java.util.Scanner;
class Animal {
String sound() { return "..."; }
}
class Dog extends Animal {
@Override
String sound() { return "Woof"; }
}
class Cat extends Animal {
@Override
String sound() { return "Meow"; }
}
class Cow extends Animal {
@Override
String sound() { return "Moo"; }
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String name = sc.next();
Animal a;
if (name.equals("dog")) a = new Dog();
else if (name.equals("cat")) a = new Cat();
else if (name.equals("cow")) a = new Cow();
else a = new Animal();
System.out.println(name + ": " + a.sound());
}
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module