In: Computer Science
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.
Area of a circle: Area = π r2, where p is Math.PI and r is
the circle's radius
Area of a rectangle: Area = Width x Length
Area of a cylinder: Area = π r2 h, where p 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.
Sample Run
java Area
===·Area·Calculator·===↵
↵
·Enter·radius·to·calculate·circle·area:2.0↵
·Enter·width·to·calculate·rectangle·area:3.5↵
·Enter·length·to·calculate·rectangle·area:4.0↵
·Enter·base·radius·to·calculate·cylinder·area:8.0↵
·Enter·height·to·calculate·cylinder·area:5.7↵
·↵
--------↵
Results:↵
--------↵
↵ The·area·of·the·circle·is:·12.57↵
The·area·of·the·rectangle·is:·14.00↵
The·area·of·the·cylinder·is:·1146.05↵
(In Java)
NOTE : PROGRAM IS DONE WITH JAVA PROGRAMMING LANGUAGE.
HERE area_shape CLASS HAS THREE OVERLOADED STATIC METHOD area() WITH DIFFERENT PARAMETERS, THEY AREA CALLED IN MAIN FUNCTION OF DRIVER CLASS overload_area.
IN overload_area CLASS THE OBJECT ob IS CREATED BY CLASS area_shape AND ALL OVERLOADED STATIC METHODS ARE EXECUTED WITH THE OBJECT ob.
PROGRAM
import java.util.Scanner;
class area_shape
{
/* static function area is overloaded with different
parameters*/
public static double area(double r)
{
double res;
res=Math.PI*r*r;
return res;
}
public static double area(double w, double h)
{
double res;
res=w*h;
return res;
}
public static double area(double r, double h,double p)
{
double res;
res=p*r*r*h;
return res;
}
}
public class overload_area
{
public static void main(String[] args)
{
double r,width,length,h,br,p;
/* scanner object */
Scanner sc=new Scanner(System.in);
/* ob is object of class area_shape*/
area_shape ob= new area_shape();
p=Math.PI;
/* console input */
System.out.println("\n=== Area Calculator
===\n");
System.out.print("Enter radius to calculate circle
area :");
r=sc.nextDouble();
System.out.print("Enter width to calculate rectangle
area:");
width=sc.nextDouble();
System.out.print("Enter length to calculate rectangle
area:");
length=sc.nextDouble();
System.out.print("Enter base radius to calculate
cylinder area:");
br=sc.nextDouble();
System.out.print("Enter height to calculate cylinder
area::");
h=sc.nextDouble();
System.out.println("\n--------------");
System.out.println("Results:");
System.out.println("--------------");
/* print result*/
System.out.printf("The area of the circle is:
%.2f\n",ob.area(r));
System.out.printf("The area of the rectangle is:
%.2f\n",ob.area(width,length));
System.out.printf("The area of the cylinder is: %.2f\n",
ob.area(br,h,p));
}
}
SCREEN SHOT
OUTPUT