In Java, when should we use private instance methods in interfaces?

sg7610 :

As of Java 9, methods in an interface can be private. A private method can be static or an instance method. Since private methods can only be used in the methods of the interface itself, their use is limited to being helper methods for the other methods of the interface.

Cay S. Horstmann, Core Java Volume I - Fundamentals

I get that we can put the common functionality in the private methods and not make it accessible to public. But we can have two kind of private methods here:

  1. private
  2. private static

Using private static methods is understandable, but when should we use private methods? We are not dealing with instances here as this is an interface, so why creating private methods is allowed? Don't we need only private static methods?

jingx :

OK, another attempt at actually answering OP's questions. When you need to call another non-static method on the interface from a private method, the private method cannot be static. For example, there would be a compilation error if the private method below was static:

public interface InterfaceWithMethods {
    public default void doSomething() {
        doSomethingCommon();
    }

    public default void doSomethingElse() {
        doSomethingCommon();
    }

    public void actuallyDoSomething();

    private void doSomethingCommon() {
        System.out.println("Do something first.");
        actuallyDoSomething();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=304492&siteId=1