015-004-008

Polymorphism with ArrayList

Medium

Problem Description

polymorphism with ArrayList

In this problem, you will create a program that defines Dog, Cat, and Bird subclasses extending Animal, overrides the speak() method in each subclass, stores instances in an ArrayList<Animal>, and displays each animal's sound to standard output by calling speak() in a loop.

Learning Objective: Understand how to store different child class objects in parent class type ArrayList

Overview

Create a program that reads animal types from standard input, stores different child class instances in parent class type ArrayList, and utilizes polymorphism.

Specifications

  • Define Animal class and its subclasses (Dog, Cat, Bird)
  • override speak() method in each class
  • Read input with Scanner, add animals to ArrayList, and output sounds in loop

Input Format

N
type1
type2
...
typeN
  • Line 1: Number of animals N (1 ≤ N ≤ 10)
  • Next N lines: Animal type (Dog, Cat, or Bird)

Output Format

Output each animal's sound on N separate lines.

  • DogWoof!
  • CatMeow!
  • BirdChirp!

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