Private Methods with Interface in Java

With Java 9:

Java 9 started supporting private methods inside interfaces, Java 9 has supports features of previous releases like default and static methods.

In this article, we learn about private methods in interfaces of the java.

The need for Private methods in java Interfaces

The private method in Interface provides the code reusability without affecting implementing classes

In interfaces, we can have default methods. Sometimes these default methods may contain a code which is common in multiple methods. In such cases, we can write another default method and make code reusability.

When the common code is internal/confidential then it is not advised to keep them on the default methods because all the classes which implement the interface can access all the default methods. So it is not advisable to keep such internal/confidential inside the default methods.

The private methods in Java are visible only inside that class/Interface, so it is better to use the private methods for confidential code. This is the reason behind the addition of private methods to Interfaces in java.

private void methodName() {
	// some code
}

For example, Interface ICherCher has two default methods, these methods have some common internal code, which is stored in a private method called division(). division() method is only accessible inside the Interface ICherCher.

interface ICherCher{
	default void addition() {
		System.out.println("default method IA");
	}
	default void multiply() {
		division();
		System.out.println("default method 'multiply'");
	}
	private void division() {
		System.out.println("I am private method in interface");
	}
}
class A implements ICherCher{
	public static void main(String[] args) {
		A a = new A();
		a.multiply();
	}
}

private-methods-interface-java

private static methods in Interfaces of Java

Java 8, started allowing static methods inside Interfaces, static methods are accessible inside default and private methods of the Interfaces. But static methods cannot access default and private methods, because of this reason, we have to use private static methods inside interface to have code reusability with encapsulation.

private static void methodName() {
	// some code
}

The complete code for private static methods inside Interfaces of Java.

interface ICherCher{
	default void multiply() {
		subtraction();
		System.out.println("default method 'multiply'");
	}
	private void division() {
		subtraction();
		System.out.println("I am private method in interface");
	}
	static void power() {
		subtraction();
	}
	private static void subtraction() {
		System.out.println("I am static inside interface");
	}
}
class A implements ICherCher{
	public static void main(String[] args) {
		A a = new A();
		a.multiply();
	}
}
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions