015-001-005
Polymorphism: Shape Drawing System
Hard
Problem Description
Polymorphism: Shape Drawing System
Learning Objective: Understand how to handle different object types uniformly using polymorphism
Overview
Polymorphism is a key OOP concept that enables different behaviors with the same interface. A parent class type variable can hold child class instances, and appropriate methods are called at runtime.
Specifications
Create abstract parent class Shape:
- abstract method
draw()(no implementation) - abstract method
getArea(): returns area (no implementation)
Create child class Circle:
- Extends
Shape - Private field
radius - Constructor accepts radius
- Implement
draw(): outputs "Drawing Circle with radius: [radius]" - Implement
getArea(): returns circle area (radius × radius × 3.14)
Create child class Rectangle:
- Extends
Shape - Private fields
widthandheight - Constructor accepts width and height
- Implement
draw(): outputs "Drawing Rectangle [width]x[height]" - Implement
getArea(): returns rectangle area (width × height)
In Main class:
- Create Shape array (Circle(radius: 5), Rectangle(width: 4, height: 6))
- Call draw() for each element
- Output area for each element in format "Area: [area]"
Output Format
Drawing Circle with radius: 5
Area: 78.5
Drawing Rectangle 4x6
Area: 24.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?
