015-003-010

Safe Downcasting with instanceof

Hard

Problem Description

Safe Downcasting with instanceof

In this problem: You will create an Animal class hierarchy (Dog and Cat), upcast elements into an Animal[] array, then safely downcast using instanceof to call subclass-specific methods.

Learning Objective: Understand safe downcasting with instanceof type checks and recognize ClassCastException risks

Overview

Create Animal as a base class with two subclasses: Dog (with bark() method) and Cat (with purr() method). Store them in an Animal[] array via upcasting, then loop through, check types with instanceof, safely downcast, and call subclass-specific methods.

Specifications

Animal Class

  • Has a protected String name field
  • Constructor Animal(String name) initializes the field
  • speak() method: outputs "[name] makes a sound"

Dog Class

  • Inherits from Animal
  • Overrides speak(): outputs "[name] says: Woof!"
  • bark() method: outputs "[name] barks loudly!"

Cat Class

  • Inherits from Animal
  • Overrides speak(): outputs "[name] says: Meow!"
  • purr() method: outputs "[name] purrs softly."

Main Class

  • Store Dog("Rex"), Cat("Whiskers"), Dog("Buddy") in an Animal[] array
  • Loop and call speak() on all elements
  • Then loop using instanceof to call bark() for Dogs and purr() for Cats

Output Format

--- Polymorphic speak() ---
Rex says: Woof!
Whiskers says: Meow!
Buddy says: Woof!
--- Safe Downcasting ---
Rex barks loudly!
Whiskers purrs softly.
Buddy barks loudly!

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