Method Overloading with Different Numbers of Parameters in Java


Create a Java program to demonstrate method overloading with two methods having different numbers of parameters

  • Class Definition: The class MathOperations is defined.
  • Method Overloading: In this class, there are two methods named add, but they differ in their parameter lists. This is called method overloading. Java allows method overloading, where you can have multiple methods with the same name but different parameters.
    • The first add method takes two integer parameters a and b and returns the sum of these two numbers.
    • The second add method takes three integer parameters a, b, and c and returns the sum of these three numbers.
  • Main Method: The main method is the entry point of the program.
  • Object Creation: An object math of the class MathOperations is created.
  • Method Calls: Two method calls are made:
    • math.add(7, 3): This calls the first add method with two integer parameters 7 and 3. The result (sum of 7 and 3) is printed.
    • math.add(5, 9, 3): This calls the second add method with three integer parameters 5, 9, and 3. The result (sum of 5, 9, and 3) is printed.

Source Code

class MathOperations
{
	int add(int a, int b)
	{
		return a + b;
	}
 
	int add(int a, int b, int c)
	{
		return a + b + c;
	}
 
	public static void main(String[] args)
	{
		MathOperations math = new MathOperations();
		System.out.println("Sum of Two Numbers : " + math.add(7, 3));
		System.out.println("Sum of Three Numbers : " + math.add(5, 9, 3));
	}
}

Output

Sum of Two Numbers : 10
Sum of Three Numbers : 17

Example Programs