7

Java 9 has two new additions to interfaces

  • private methods
  • private static methods

Now, I get the need for private methods in interfaces. You want to use the method inside the interface but not let it be accessed from outside the interface.

I also understand the use of private static methods in Java classes. You want it to be private so that it can only be accessed only from inside the class and static, so that it can be used without initialising the class.

In that case, what is the purpose of a private static method in an interface? Considering that, you can achieve the accessibility part by a private method in interface and that an interface can anyways be not initialized, so no need for it to be static.

What's the difference between private methods and private static methods in an interface. Moreover, what's the need for private static methods in an interface?

Aniket Paul
  • 233
  • 1
  • 11
  • 5
    Do you understand why public static methods in interfaces can be useful? If so, why couldn't these methods be refactored and made simpler by delegating to other, private, static methods? – JB Nizet Apr 01 '18 at 06:40
  • Yes, I know about public static methods in interfaces. They are not inherited and can only be accessed outside using interface name. So private static methods help in refactoring public static methods? – Aniket Paul Apr 01 '18 at 07:03
  • 3
    private (and public) static methods in interfaces have exactly the same features as private (and public) static methods on classes. – JB Nizet Apr 01 '18 at 07:15
  • 3
    @JBNizet no they don't, public static from interfaces are not inherited – Eugene Apr 01 '18 at 15:19

1 Answers1

4

Private static methods are useful when you have multiple public static methods that share some common code. So, you can only extract that shared code into a static method, but not into an instance method.

interface Example {

    static void doJob1(String arg) {
        verifyArg(arg);
        ...
    }

    static void doJob2(String arg) {
        verifyArg(arg);
        ...
    }

    private static void verifyArg(String arg) {
        ...
    }
}
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
  • Thanks, I get this. So, is this the only use for a private static method in an interface or are there any other ones as well? – Aniket Paul Apr 01 '18 at 07:05