The problem
Write a class that has three overloaded static methods for calculating the areas of the following geometric shapes:
- circles
- rectangles
- cylinders
Here are the formulas for calculating the area of the shapes:
Shape | Formula |
---|---|
Area of a circle | Area = nr^2 where: n is Math.PI and r is the circle's radius |
Area of a rectangle | Area = Width x Length |
Area of a cylinder | Area = nr^2h where: n is Math.PI, r is the radius of the cylinder's base, and h is the cylinder's height |
Because the three methods are to be overloaded, they should each have the same name, but different parameter lists. Demonstrate the class in a complete program.
Breaking it down
Area class
public static class Area {
/**
* Method should calculate the area of a circle
*
* @param radius
* @return area of a circle
*/
public static double getArea(double radius) {
return Math.PI * radius * radius;
}
/**
* Method should calculate the area of a rectangle
*
* @param length
* @param width
*
* @return area of a rectangle
*/
public static double getArea(int length, int width) {
return length * width;
}
/**
* Method should calculate the area of a cylinder
*
* @param radius
* @param height
*
* @return area of a cylinder
*/
public static double getArea(double radius, double height) {
return Math.PI * radius * radius * height;
}
}
Main program
public static void main(String[] args) {
// Area of a circle
System.out.printf("The area of a circle with a "
+ "radius of 10.0 is %6.2f\n", Area.getArea(10.0));
// Area of a rectangle
System.out.printf("The area of a rectangle with a "
+ "length of 15 and a width of 25 is %6.2f\n",
Area.getArea(15, 25));
// Area of cylinder
System.out.printf("The area of a cylinder with a "
+ "radius of 12.0 and a height " + "of 17.0 is %6.2f\n",
Area.getArea(12.0, 17.0));
}
Output
The area of a circle with a radius of 10.0 is 314.16
The area of a rectangle with a length of 15 and a width of 25 is 375.00
The area of a cylinder with a radius of 12.0 and a height of 17.0 is 7690.62
Level Up
- Write three unit tests for each
getArea
overloaded method validating the logic in the method is correct.