015-003-008

Basics of instanceof and Downcasting

Easy

Problem Description

Basics of instanceof and Downcasting

In this problem, you will create a program that reads dog and cat names from standard input, checks the types of Dog and Cat objects stored in an Animal array using instanceof, downcasts them to call subclass-specific methods (fetch() and purr()), and displays the result to standard output.

Learning Objective: Understand using instanceof for type checking and downcasting to call subclass-specific methods

Overview

Read animal names from standard input, store them in an Animal array, check the actual type of each object using instanceof, then downcast to call subclass-specific methods.

Specifications

  1. Define String name field and constructor in Animal class
  2. Dog extends Animal, fetch() prints <name> fetches the ball!
  3. Cat extends Animal, purr() prints <name> purrs...
  4. In main, read the dog's name on the first line and the cat's name on the second line from standard input
  5. Store Dog(dogName) and Cat(catName) in an Animal array
  6. Loop and check type with instanceof, call appropriate method

Input Format

<dog name>
<cat name>

Output Format

<dog name> fetches the ball!
<cat name> purrs...

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