015-001-009

Polymorphism: Method Override

Medium

Problem Description

polymorphism: method override

In this problem, you will create a program that defines Animal, Dog, and Cat classes with overridden makeSound() methods, reads a sequence of animal type names from standard input, and outputs each animal's sound through the same method call on parent-type variables.

Learning Objective: Understand how to override parent class methods in subclasses and achieve different behaviors from the same method call

Overview

In polymorphism, a parent class type variable can reference a subclass object. When an overridden method is called, the behavior corresponding to the actual object type is executed.

Specifications

Create the following classes:

Animal class:

  • makeSound() method: outputs "Some sound"

Dog class (extends Animal):

  • Override makeSound(): outputs "Woof!"

Cat class (extends Animal):

  • Override makeSound(): outputs "Meow!"

Main class:

  1. Read the number N of animals from standard input
  2. Read N lines, each containing an animal type ("Animal", "Dog", or "Cat")
  3. Assign each object to an Animal type variable and call makeSound()

Input Format

N
animal type 1
animal type 2
...
  • Line 1: Number of animals N (at least 1)
  • Subsequent lines: Animal type (one of "Animal", "Dog", "Cat")

Output Format

Output of makeSound() for each animal (N lines)

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