Create Private Methods in Java 9

We can create private methods inside Interface in Java 9 onwards. Until Java 8 we create default and static methods inside Interface. Prior to Java 8 interface is having abstract methods declared.

Table of content  

1. Need for a Private Method inside the interface in Java 9
2. How to Declare Java 9 private method in Interface? 
3. Java 9 private method inside the Interface Interface Example
4. Java 9 private static method inside the Interface Interface Example
5. Conclusion

1. Need for a Private Method inside the interface in Java 9

If several default methods have the same common functionality then there may be a change of duplicate code is there. Interface static method call by interface name only. To resolve these limitations of default and static methods in Interface. Java introduced private methods inside Interface in Java 9. Interfaces are able to hide the detailed implementation of methods from implementation classes of that interfaces by using this Java 9 feature.

2. How to Declare Java 9 private method in Interface? 

public interface Interface_Name{
private  return_type  method_name(){
}
private static return_type  method_name(){
 }
}


3. Java 9 private method inside the Interface Example

interface InterF {
  default void msg() {
    sayHi();
  }
  //private method inside interface  
  private void sayHi() {
    System.out.println("-------private method()----------");
  }
}
public class Test implements InterF {
  public static void main(String[] args) {
    InterF interF = new Test();
    interF.msg();
  }
}

Output

-------private method()----------

4. Java 9 private static method inside the Interface Example

interface InterF {
  default void msg() {
    sayHi();
    say();
  }
  // private method inside interface  
  private void sayHi() {
    System.out.println("-------private method()----------");
  }

  //private static method inside interface  
  private static void say() {
    System.out.println("---------private static method()----------");
  }
}
public class Test implements InterF {
  public static void main(String[] args) {
    InterF interF = new Test();
    interF.msg();
  }
}

Output

-------private method()----------
---------private static method()----------

5. Conclusion

In this topic, we learnt about Java 9 Private methods inside the Interface feature.

Leave a Comment