015-005-009
instanceof and Downcasting
Medium
Problem Description
instanceof and Downcasting
In this problem, you will create a program that reads shape data from standard input, checks each element with instanceof, safely downcasts to Circle or Square, and calls type-specific methods, displaying the result to standard output.
Learning Objective: Understand how to safely downcast after checking type with instanceof
Overview
Create a program that reads shape data from standard input, safely downcasts parent type variables to child types, and calls child-specific methods.
Specifications
- Define Shape class and its subclasses (Circle, Square)
- Add getRadius() to Circle, getSide() to Square
- Read shape data from standard input and store in a Shape-type list
- Check each element with instanceof and call appropriate method
Input Format
N
Type1 value1
Type2 value2
...
- Line 1: number of shapes N
- Next N lines: shape type (Circle or Square) and value (decimal) separated by space
Output Format
Circle radius: 5.0
Square side: 4.0
Circle radius: 3.0
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