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 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

Check the actual type of objects stored in Animal type variables 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, store Dog("Rex") and Cat("Mimi") in Animal array
  5. Loop and check type with instanceof, call appropriate method

Output Format

Rex fetches the ball!
Mimi 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