Tuesday, October 03, 2017

Java 9 : Private interface methods

Java 8 introduced default and static methods, the previous post gives a few examples of Java 8 default and static methods. Java 9 builds on that foundation and adds support for private interface methods. In this post, we will see a simple example of how to use private methods to interfaces. In general,
  1. Like any private method, private interface methods are accessible from within the enclosing interface only.
  2. Private methods can be declared using the private keyword.
  3. Any private method has to be implemented in the interface as it cannot implemented in a sub-interface or implementing classes.
The following example shows how to create a private method in the interface and a default method calling it.
package interfaces;

public interface InterfaceA {

 default String hello(String str) {
  return privateAddon("InterfaceA : hello " + str);
 private String privateAddon(String str) {
  return "Private Addon : " + str;
The following is a simple implementation class of this interface
package interfaces;

public class PrivateInterfaceMethods implements InterfaceA {
 public static void main(String[] args) {
  PrivateInterfaceMethods example = new PrivateInterfaceMethods();



Popular Posts