Write a program that implements three classes: “Shape” class, “Circle” class, an
ID: 673901 • Letter: W
Question
Write a program that implements three classes: “Shape” class, “Circle” class, and the “Square” class. The Circle class and the square class are to be subclasses of the super class Shape. Declare an object of type ArrayList in the main method. The ArrayList’s object should hold two Circle-type objects and three Square-type objects. Your code should implements the following list of methods:
a. GetArea ( ): an overridden method implemented in the child classes, Circle and Square. The method will return the area of the object
b. GetMin ( ): a method that returns the object that have the minimum area among the list of stored objects
c. GetMax ( ): a method that return the object that have the maximum area among the list of stored objects
In your driver or main method test your code by adding two circle and three square objects to the ArrayList’s object.
Explanation / Answer
Complete Program:
// TestShapes class
import java.util.ArrayList;
public class TestShapes
{
public static void main(String[] args)
{
ArrayList<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Circle(1));
shapes.add(new Circle(2));
shapes.add(new Square(5));
shapes.add(new Square(2));
shapes.add(new Square(3));
System.out.println("GetMin(): " + GetMin(shapes));
System.out.println("GetMax(): " + GetMax(shapes));
}
public static double GetMin(ArrayList<Shape> shapes)
{
double minArea = shapes.get(0).GetArea();
for(int i = 1; i < shapes.size(); i++)
{
double currArea = shapes.get(i).GetArea();
if(currArea < minArea)
minArea = currArea;
}
return minArea;
}
private static double GetMax(ArrayList<Shape> shapes)
{
double maxArea = shapes.get(0).GetArea();
for(int i = 1; i < shapes.size(); i++)
{
double currArea = shapes.get(i).GetArea();
if(currArea > maxArea)
maxArea = currArea;
}
return maxArea;
}
}
// Circle class
public class Circle extends Shape
{
private double radius;
public Circle(double r)
{
super();
radius = r;
}
public double GetArea()
{
return Math.PI * radius * radius;
}
}
// Square class
public class Square extends Shape
{
private double side;
public Square(double a)
{
super();
side = a;
}
public double GetArea()
{
return side * side;
}
}
// Shape class
public class Shape
{
public Shape()
{}
public double GetArea()
{
return 0;
}
}
Sample Output:
GetMin(): 3.141592653589793
GetMax(): 25.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.