Private interface methods are supported by Java 9.
This support allows non-abstract methods of an interface
to share code between them. Private methods can be static or instance.
Can private methods of an interface be abstract
or default
?
May I ask for an example where "private static
interface methods" are useful in terms of code?
No, the private methods in the interfaces are supposedly designed for clubbing in a piece of code that is internal to the
interface
implementation. Since these pertain to the implementation(consist of a body) and not the declaration it can neither bedefault
and norabstract
when defined.A
private
method is astatic
method or a non-default instance method that's declared with theprivate
keyword. You cannot declare adefault
method to also beprivate
becausedefault
methods are intended to be callable from the classes that implement their declaring interfaces.The
private static
methods are useful in abstracting a common piece of code fromstatic
methods of an interface while defining its implementation.Example of a private static method in an interface could be as follows. Consider an object,
Question.java
on StackOverflow defined as:and an interface that proposes the sort by functionality as seen in the listed questions on
StackOverflowTag
:Here the
private static
methodsortBy
of the interface internally implements the sorting based on thesortOrderType
sharing the implementation with two public static methods of the interface which can be further consumed by aStackOverflowTagConsumer
can simply access these interface static methods as :