Private interface methods, example use-case?

Why not simply (simply = using Java8):

PS: because of private helper is not possible in Java

public interface MyInterface {
 private static class Helper{
     static initializeMyClass(MyClass myClass, Params params){
         //do magical things in 100 lines of code to initialize myClass for example
     }
 }

 default MyClass createMyClass(Params params) {
     MyClass myClass = new MyClass();
     Helper.initializeMyClass(myClass, params);
     return myClass;
 }

 default MyClass createMyClass() {
     MyClass myClass = new MyClass();
     Helper.initializeMyClass(myClass, null);
     return myClass;
 }
}

Java 9 allows declaring a private method inside the interface. Here is the example of it.

interface myinterface {
    default void m1(String msg){
        msg+=" from m1";
        printMessage(msg);
    }
    default void m2(String msg){
        msg+=" from m2";
        printMessage(msg);
    }
    private void printMessage(String msg){
        System.out.println(msg);
    }
}
public class privatemethods implements myinterface {
    public void printInterface(){
        m1("Hello world");
        m2("new world");
    }
    public static void main(String[] args){
        privatemethods s = new privatemethods();
        s.printInterface();
    }
}

For that, you need to update jdk up to 1.9 version.


Interfaces can now have default methods. These were added so that new methods could be added to interfaces without breaking all classes that implement those changed interfaces.

If two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method and all its "implementation details" via the interface.