015-002-008

Achieving Polymorphism with Upcasting

Easy

Problem Description

Achieving polymorphism with Upcasting

In this problem, you will create a program that reads animal types with Scanner, uses upcasting to assign Dog or Cat objects to Animal type variables, then calls the same speak() method on each to produce different output per subclass.

Learning Objective: Understand the basics of upcasting (treating subclass as superclass type)

Overview

Read animal types (Dog or Cat) from Scanner input, assign the corresponding objects to Animal type variables, and call speak() to demonstrate polymorphism.

Input Format

N
type1
type2
...
typeN
  • N: number of animals (at least 1)
  • typeX: Dog or Cat

Specifications

  1. Define void speak() in Animal class (prints ...)
  2. Dog extends Animal, overrides speak() to print Woof!
  3. Cat extends Animal, overrides speak() to print Meow!
  4. In main, read input with Scanner, assign the appropriate object to an Animal type variable, and call speak()

Input/Output Example

Input:

2
Dog
Cat

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