Java Program to calculate the area of Circle, rectangle, Square using method Overloading.
Objective
Calculate the area of a Circle, Rectangle, and Square using Method Overloading.
Algorithm / Approach
- Create an
Areaclass. - Define
area(double r)to calculate the area of a circle (PI * r * r). - Define
area(int a, int b)to calculate the area of a rectangle (a * b). - Define
area(int a)to calculate the area of a square (a * a). - In main, call the
area()method three times, passing different sets of arguments.
Area.java
class Area {
void area(double r) {
double ar = 3.14*r*r;
System.out.println("Cirlce Area = "+ar);
}
void area(int a, int b) {
int ar = a*b;
System.out.println("Rectangle Area = "+ar);
}
void area(int a) {
double ar = a*a;
System.out.print("Square Area = "+ar);
}
public static void main(String[] a)
{
Area obj = new Area();
obj.area(4.5);
obj.area(3,4);
obj.area(5);
}
}
Expected Output
Cirlce Area = 63.585 Rectangle Area = 12 Square Area = 25.0
Explanation of the Program
- This program perfectly demonstrates why method overloading is useful. Instead of forcing the programmer to remember three different method names (like
circleArea(),rectArea(),squareArea()), we just use one intuitive name:area(). - The compiler automatically knows which mathematical formula to execute based on whether you pass one decimal (Circle), two integers (Rectangle), or one integer (Square).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)