What are the advantages of private methods in an interface in Java 9?

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 20-Feb-2020 12:22:40
Advertisements