015-001-010
Basic Polymorphism
Hard
Problem Description
Basic polymorphism
In this problem, you will create a program that defines an Animal class and two subclasses (Dog, Cat), reads animal types from standard input, stores them in an Animal-type array, and calls speak() polymorphically.
Learning Objective: Understand method overriding and basic polymorphism behavior
Overview
Polymorphism allows parent type references to hold child class objects. At runtime, the overridden method in the child class is called.
Specifications
- Define speak() method in Animal class (displays "...")
- Dog extends Animal and overrides speak() (displays "Woof!")
- Cat extends Animal and overrides speak() (displays "Meow!")
- Read the number of animals and their types from standard input, store in an Animal array, and call speak() in a loop
Input Format
n
animalType1
animalType2
...
- First line: number of animals n
- Next n lines: type of each animal (one of "Animal", "Dog", "Cat")
Output Format
Print the output of speak() for each animal, one per line.
Sample Input
3
Animal
Dog
Cat
Sample Output
...
Woof!
Meow!
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up