private interface methods in java 9:

It’s now possible to add private methods in interfaces in Java 9. In this guide we explained in detailed about interface private methods in java 9.

Allowed modifiers for interface methods until Java 7:

Until java 7 every interface method is public and abstract by definition, means these modifiers whether we declared or not every interface method is public and abstract. As every interface method is always public and abstract we can’t use the following modifiers for interface methods.
private, protected, final, static, synchronized, native, strictfp.

Allowed modifiers for interface methods in Java 8:

In java 8 in addition to public and abstract modifiers, default, static and strictfp also permitted for interface methods.

Allowed modifiers for interface methods in Java 9:

In Java 9, In addition to the above modifiers private also permitted to use as modifier for interface methods. Below are all the permitted modifiers for interface methods.

private, public, abstract, default, static and strictfp.

Rules for writing private methods in java 9:

  1. Private interface method modifier combination with private and abstract not allowed.
  2. Private method can be used only inside interface, cant be inherited or accessible out side of interface.
  3. Generally as static methods can call from both static and instance area, private static methods can be called from inside instance method or static method inside interface.
  4. private non-static method is not allowed to call from static method with in interface. In general instance methods can’t be called from static context with in class or interface.
  5. private strictfp combination also allowed for interface methods in java 9, but strictfp with abstract combination not permitted. strictfp is very rarely used modifier in java. strictfp means strictly floating point that ensures that you get exactly the same results from your floating point calculations on every platform. This is out of scope of current topic, for more read on strictfp follow FP Strict.

Use of private methods in interfaces in Java 9:

  1. Code re usability. Since java 8 the default and static methods also valid inside interfaces, if any piece of code re usable for multiple methods with in same interface instead of writing that re usable code out side of interface, we can write private method and that can be re used with in the interface.
  2. Also can achieve the hiding the implementation of methods and then expose only methods that you want show to client.

Example to demonstrate private interface methods in Java 9 :