Private interface methods, example use-case?

EpicPandaForce picture EpicPandaForce · Mar 13, 2015 · Viewed 12.7k times · Source

"Support for private methods in interfaces was briefly in consideration for inclusion in Java SE 8 as part of the effort to add support for Lambda Expressions, but was withdrawn to enable better focus on higher priority tasks for Java SE 8. It is now proposed that support for private interface methods be undertaken thereby enabling non abstract methods of an interface to share code between them."

So says the specification for http://openjdk.java.net/jeps/213 and says in bug report https://bugs.openjdk.java.net/browse/JDK-8071453 .

But I can't really think of any use-case where this is necessary, even with the short explanation given above. May I ask for an example where "private interface methods" are useful in terms of code?

EDIT: So the answer is that due to how default implementations have been added to interfaces in Java 8, there can be instances where the default implementations are using the same codebase.

For example,

public interface MyInterface {
     default void 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();
         initializeMyClass(myClass, params);
         return myClass;
     }

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

Silly example, I know. But let's say that we want to use initializeMyClass(MyClass, Params) in both methods. However, if we do it like this (default method), then initializeMyClass(MyClass, Params) will be part of the public interface! To prevent that from happening, we can only keep the code of entire initializeMyClass(MyClass, Params) inside the createMyClass() default methods. Which results in code duplication, which is undesirable.

Therefore, this causes problem with refactoring, and to remove such code duplication, private default methods are allowed.

Thanks for answering!

Answer

mk. picture mk. · Mar 13, 2015

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.