Static Methods in Interfaces in Java


Write a Java program to demonstrate the use of static methods in interfaces

  • MathOperation is an interface containing two static methods: add() and subtract().
  • Both add() and subtract() methods perform addition and subtraction, respectively, and return the result.
  • In the Main class, the add() and subtract() methods are called directly on the interface MathOperation using the static method invocation syntax (MathOperation.add() and MathOperation.subtract()).
  • The results of the addition and subtraction operations are then printed to the console.

Source Code

interface MathOperation
{
	static int add(int a, int b)
	{
		return a + b;
	}
 
	static int subtract(int a, int b)
	{
		return a - b;
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		int sum = MathOperation.add(4, 7);
		int sub = MathOperation.subtract(10, 3);
		System.out.println("Addition : " + sum);
		System.out.println("Subtraction : " + sub);
	}
}

Output

Addition : 11
Subtraction : 7

Example Programs