Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need for private static methods in interfaces - Java 9 [duplicate]

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?

like image 708
Aniket Paul Avatar asked Apr 01 '18 06:04

Aniket Paul


1 Answers

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) {
        ...
    }
}
like image 190
ZhekaKozlov Avatar answered Nov 07 '22 01:11

ZhekaKozlov