Java 9 added a new feature of private methods to an interface. The private methods can be defined using a private modifier. We can add both private and private static methods in an interface from Java 9 onwards.
Rules for private methods in an interface:
- A private method has a body in an interface means that we can’t be declared as a normal abstract method as usually do in an interface. If we are trying to declare a private method without a body then it can throw an error says that "This method requires a body instead of a semicolon".
- We can't be used both private and abstract modifiers together in an interface.
- If we want to access a private method from a static method in an interface then that method can be declared as a private static method as we can’t make a static reference to the non-static method.
- A private static method used from a non-static context means that it can be invoked from a default method in an interface.
Syntax
interface <interface-name> {
private methodName(parameters) {
// some statements
}
}Example
interface TestInterface {
default void methodOne() {
System.out.println("This is a Default method One...");
printValues(); // calling a private method
}
default void methodTwo() {
System.out.println("This is a Default method Two...");
printValues(); // calling private method...
}
private void printValues() { // private method in an interface
System.out.println("methodOne() called");
System.out.println("methodTwo() called");
}
}
public class PrivateMethodInterfaceTest implements TestInterface {
public static void main(String[] args) {
TestInterface instance = new PrivateMethodInterfaceTest();
instance.methodOne();
instance.methodTwo();
}
}Output
This is a Default method One... methodOne() called methodTwo() called This is a Default method Two... methodOne() called methodTwo() called