Method Overloading with Multiple Parameters of the Same Data Type in Java


Write a Java program to demonstrate method overloading with multiple parameters of the same data type

This Java program demonstrates method overloading in a class named Geometry, which calculates the area of rectangles and squares. Let's break down the code:

  • The main method creates an instance of the Geometry class.
  • It then calls the area methods with different arguments.
  • The Java compiler determines which overloaded method to call based on the number and type of arguments passed.
  • For the first call, geo.area(8, 3), the area(int length, int width) method is invoked, calculating the area of a rectangle.
  • For the second call, geo.area(7), the area(int side) method is invoked, calculating the area of a square.
  • The calculated areas are then printed to the console.

Source Code

class Geometry
{
	int area(int length, int width)
	{
		return length * width;
	}
 
	int area(int side)
	{
		return side * side;
	}
 
	public static void main(String[] args)
	{
		Geometry geo = new Geometry();
		System.out.println("Area of Rectangle : " + geo.area(8, 3));
		System.out.println("Area of Square : " + geo.area(7));
	}
}

Output

Area of Rectangle : 24
Area of Square : 49

Example Programs