Need for private static methods in interfaces - Java 9

Aniket Paul :

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?

ZhekaKozlov :

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) {
        ...
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=468565&siteId=1