Why do we need private methods in an interface in Java 9?

JavaObject Oriented ProgrammingProgramming

An interface supports default methods since Java 8 version. Sometimes these default methods may contain a code that can be common in multiple methods. In those situations, we can write another default method and make code reusability. When the common code is confidential then it's not advisable to keep them in default methods because all the classes that implement that interface can access all default methods.

An interface can have private methods since Java 9 version. These methods are visible only inside the class/interface, so it's recommended to use private methods for confidential code. That's the reason behind the addition of private methods in interfaces.

Syntax

private void methodName() {
   // some statementscode
}

Example

interface Operation {
   default void addition() {
      System.out.println("default method addition");
   }
   default void multiply() {
      division();
      System.out.println("default method multiply");
   }
   private void division() {         // private method
      System.out.println("private method division");
   }
}

class PrivateMethodTest implements Operation {
   public static void main(String args[]) {
      PrivateMethodTest test = new PrivateMethodTest();
      test.multiply();
   }
}

Output

private method division
default method multiply
raja
Published on 28-Feb-2020 11:45:00
Advertisements