014-005-001

Method Overriding: Animal Sounds

Easy

Problem Description

Method Overriding: Animal Sounds

In this problem, you will create a program that defines an Animal parent class with a speak() method, then creates Dog and Cat subclasses that each override speak() using the @Override annotation. The program reads animal types from input and displays each animal's sound.

Learning Objective: Redefine parent method in child class with @Override

Create Animal class representing animals and Dog/Cat classes inheriting from it. Override parent's speak() method in child classes to output different sounds.

Input

Line 1: Number of animals N (N ≥ 1)
Next N lines: Animal type ("dog" or "cat")

Output

Print each animal's sound on a separate line.

  • dog: Dog says: Woof!
  • cat: Cat says: Meow!

Examples

Example 1: Dog then cat

Input:

2
dog
cat

Output:

Dog says: Woof!
Cat says: Meow!

Example 2: Cat then dog

Input:

2
cat
dog

Output:

Cat says: Meow!
Dog says: Woof!

How Overriding Works

  • Define speak() method in parent class Animal
  • Redefine speak() with @Override in child class Dog
  • Similarly redefine in child class Cat
  • When calling speak() on each instance, the respective child class implementation executes.

Test Cases

※ Output examples follow programming industry standards

Normal case
Input:
1
cat
Expected Output:
Cat says: Meow!
Normal case
Input:
3
cat
dog
cat
Expected Output:
Cat says: Meow!
Dog says: Woof!
Cat says: Meow!

Your Solution

Current Mode: My Code
Animal.java🔒
Dog.java🔒
Cat.java🔒
Solution.java🔒
4/6 ファイル813B
public class Animal {
public void speak() {
// Override this method in subclasses
}
}
0 B / 5 MB

You have 10 free executions remaining