015-003-009

Safe Downcasting and ClassCastException

Hard

Problem Description

Safe Downcasting and ClassCastException

Learning Objective: Understand the cause of ClassCastException from improper downcasting and how to handle it

In this problem, you will create a program that reads animal types and names from standard input, uses the instanceof operator to safely downcast Animal objects to Dog or Cat, and displays the animal type and name to standard output.

Overview

Read animal data from standard input, perform safe downcasting on Animal type objects, and print a message for each.

Input Format

N
type1 name1
type2 name2
...
typeN nameN
  • N: number of animals (at least 1)
  • type: one of Dog, Cat, or Animal
  • name: the animal's name

Specifications

  1. Define Animal, Dog (extends Animal), and Cat (extends Animal) classes
  2. Define safeCast(Animal a) static method:
    • If Dog, cast and print Dog: <name>
    • If Cat, cast and print Cat: <name>
    • Otherwise, print Unknown: <name>
  3. In main, use Scanner to read input, create Dog/Cat/Animal objects based on type, and call safeCast for each

Sample Input

3
Dog Rex
Cat Mimi
Animal Unknown

Sample Output

Dog: Rex
Cat: Mimi
Unknown: Unknown

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