Interfaces with Private Methods in Java


Write a Java program to demonstrate the concept of an interface with private methods

  • The MyInterface interface contains an abstract method abstractMethod(), a default method defaultMethod(), and a static method staticMethod().
  • Both the default and static methods use private methods privateMethod() and privateStaticMethod() respectively for code reuse and encapsulation.
  • We demonstrate calling these methods from an anonymous class implementing MyInterface and from the InterfaceWithPrivateMethodsDemo class.

Source Code

public class InterfaceWithPrivateMethodsDemo
{
	public static void main(String[] args)
	{
		MyInterface myObject = new MyInterface()
		{
			@Override
			public void abstractMethod()
			{
				System.out.println("Implementation of the Abstract Method");
			}
		};
 
		myObject.abstractMethod();
		myObject.defaultMethod();
		MyInterface.staticMethod();
	}
}
 
interface MyInterface
{
	void abstractMethod();// Public abstract method
 
	default void defaultMethod()// Default method using a private method
	{
		System.out.println("Default Method");
		privateMethod();
	}
 
	static void staticMethod()// Static method using a private method
	{
		System.out.println("Static Method");
		privateStaticMethod();
	}
 
	private void privateMethod()// Private method for default methods
	{
		System.out.println("Private Method used in a Default Method");
	}
 
	private static void privateStaticMethod()// Private static method for static methods
	{
		System.out.println("Private Static Method used in a Static Method");
	}
}

Output

Implementation of the Abstract Method
Default Method
Private Method used in a Default Method
Static Method
Private Static Method used in a Static Method

Example Programs