015-002-009
Using Upcasting with Arrays
Medium
Problem Description
Using Upcasting with Arrays
In this problem, you will create a program that reads a circle's radius and a rectangle's width and height from standard input, stores Circle and Rectangle instances into a Shape type array via upcasting, then calls each object's area() method through polymorphism in a loop and displays the areas to standard output.
Learning Objective: Understand storing subclasses in superclass type arrays and processing with loops
Overview
Read radius, width, and height from standard input. Store Circle and Rectangle in a Shape array and call area() in a loop.
Input Format
<radius>
<width>
<height>
- Line 1: Circle's radius (double)
- Line 2: Rectangle's width (double)
- Line 3: Rectangle's height (double)
Specifications
- Define
double area()inShapeclass (returns 0.0) Circleextends Shape, receivesdouble radiusvia constructor, area() returns3.14 * radius * radiusRectangleextends Shape, receivesdouble width, height, area() returnswidth * height- In main, read values from Scanner, store Circle(radius) and Rectangle(width, height) in Shape array
- Loop and call area() on each, printing
Area: <area>
Output Format
Area: <circle_area>
Area: <rectangle_area>
Sample I/O
Input:
5.0
3.0
4.0
Output:
Area: 78.5
Area: 12.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