015-004-009
ArrayList with Polymorphism for Shape Management
Hard
Problem Description
ArrayList with Polymorphism for Shape Management
In this problem: You will create Circle and Rectangle classes implementing a Shape interface, store them in an ArrayList, and perform filtering and sorting by area.
Learning Objective: Understand practical data manipulation combining polymorphism with dynamic lists
Overview
Store multiple different objects in an ArrayList using an interface type and process them uniformly through polymorphism. Implement filtering by area threshold and sorting using the Streams API.
Specifications
Shape Interface
- Defines a
double getArea()method
Circle Class (implements Shape)
- Field:
double radius - Constructor: Takes
radius getArea(): ReturnsMath.PI * radius * radiustoString(): Format"Circle(radius=X.X, area=Y.YY)"(area to 2 decimal places)
Rectangle Class (implements Shape)
- Fields:
double width,double height - Constructor: Takes
widthandheight getArea(): Returnswidth * heighttoString(): Format"Rectangle(width=X.X, height=Y.Y, area=Z.ZZ)"(area to 2 decimal places)
Main Class
- Add Circles and Rectangles to
ArrayList<Shape>:new Circle(5.0)new Rectangle(3.0, 4.0)new Circle(2.0)new Rectangle(6.0, 3.0)new Circle(4.0)
- Print "All shapes:" followed by each shape on a separate line
- Print an empty line
- Filter shapes with area >= 15.0 and sort by area ascending
- Print "Shapes with area >= 15.00 (sorted):" followed by matching shapes
Output Format
All shapes:
Circle(radius=5.0, area=78.54)
Rectangle(width=3.0, height=4.0, area=12.00)
Circle(radius=2.0, area=12.57)
Rectangle(width=6.0, height=3.0, area=18.00)
Circle(radius=4.0, area=50.27)
Shapes with area >= 15.00 (sorted):
Rectangle(width=6.0, height=3.0, area=18.00)
Circle(radius=4.0, area=50.27)
Circle(radius=5.0, area=78.54)
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