Private Static Methods in Interfaces in Java


Create a Java program to demonstrate the use of an interface with a private static method

  • The MathUtils interface contains a static method add to add two integers, a private static method multiply to multiply two integers, and a default method addAndMultiply which adds the result of add and multiply.
  • In the Main class, an anonymous class is created that implements the MathUtils interface. This is necessary because static methods cannot be directly accessed through the interface name.
  • The addAndMultiply method is invoked on the math object, which adds and multiplies two integers using the default method defined in the interface.

Source Code

interface MathUtils
{
	static int add(int a, int b)
	{
		return a + b;
	}
 
	private static int multiply(int a, int b)
	{
		return a * b;
	}
 
	default int addAndMultiply(int a, int b)
	{
		return add(a, b) + multiply(a, b);
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		MathUtils math = new MathUtils() {};
		System.out.println("Result : " + math.addAndMultiply(5, 6));
	}
}

Output

Result : 41

Example Programs