In Java 9, an interface can also have private methods. Apart from static and default methods in Java 8, this is another significant change as it allows the re-usability of common code within the interface itself.
In an interface, there is a possibility of writing common code on more than one default method that leads to code duplication. The introduction of private methods avoids this code duplication.
Advantages of private methods in an interface
- Avoiding code duplication.
- Ensuring code re-usability.
- Improving code readability.
Syntax
interface interfacename { private methodName(parameters) { // statements } }
Example
interface Test { default void m1() { common(); } default void m2() { common(); } private void common() { System.out.println("Tutorialspoint"); } } public class PrivateMethodTest implements Test { public static void main(String args[]) { Test test = new PrivateMethodTest(); test.m1(); test.m2(); } }
Output
Tutorialspoint Tutorialspoint