Method Overloading with Methods That Have Different Parameter Modifiers Including Static and Non-Static in Java


Create a Java program to demonstrate method overloading with methods that have different parameter modifiers, including static and non-static

  • In the Main class's main method, we directly call the static method Calculator.add(4, 7) to calculate the sum of two integers. Static methods belong to the class itself, not to any particular instance, so they are called using the class name.
  • Then, we create an instance of the Calculator class using Calculator calculator = new Calculator();.
  • We call the instance method calculator.add(5, 10, 15) to calculate the sum of three integers. Instance methods are called on objects of the class.
  • Both static and instance methods have the same name (add), but they differ in their usage: static methods are called using the class name, while instance methods are called using an object of the class.
  • This demonstrates method overloading, where the same method name add is used with different parameter lists (number or types of parameters). Depending on how it's called (either statically or using an object), the appropriate method (static or instance) will be invoked.

Source Code

public class Main
{
	public static void main(String[] args)
	{
		System.out.println("Sum of Two Integers (static method) : " + Calculator.add(4, 7));
		Calculator calculator = new Calculator();
		System.out.println("Sum of Three Integers : " + calculator.add(5, 10, 15));
	}
}
class Calculator
{
	static int add(int a, int b)
	{
		return a + b;
	}
 
	int add(int a, int b, int c)
	{
		return a + b + c;
	}
}

Output

Sum of Two Integers (static method) : 11
Sum of Three Integers : 30

Example Programs