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

  1. Define double area() in Shape class (returns 0.0)
  2. Circle extends Shape, receives double radius via constructor, area() returns 3.14 * radius * radius
  3. Rectangle extends Shape, receives double width, height, area() returns width * height
  4. In main, read values from Scanner, store Circle(radius) and Rectangle(width, height) in Shape array
  5. 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