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
- Define
String namefield and constructor inAnimalclass Dogextends Animal,fetch()prints<name> fetches the ball!Catextends Animal,purr()prints<name> purrs...- In main, read the dog's name on the first line and the cat's name on the second line from standard input
- Store
Dog(dogName)andCat(catName)in an Animal array - 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