Java 9 — Interfaces
Java 9 introduced private
methods and private static
method in interfaces. In Java 9 an interface can have seven different things:
- constant variables (since Java 1.0)
abstract
methods (since Java 1.0)- nested types (since Java 2.0)
default
methods (since Java 8.0)static
methods (since Java 8.0)private
methods (since Java 9.0)private static
methods (since Java 9.0)
The private
methods added in Java 9.0 improve code re-usability inside interfaces and provide choice to expose only intended method implementations to users. The private
methods are only accessible within an interface and cannot be accessed or inherited from the interface to another interface or class.
Note:-
- Every field declaration in the body of an interface is implicitly
public
,static
, andfinal
. It is permitted to redundantly specify any or all of these modifiers for such fields. - Every method declaration in an interface with body represented by a semicolon is implicitly
public
andabstract
.It is a compile-time error if a method declaration that contains the keywordabstract
also contains any one of the keywords:private
,static
,final
,native
,strictfp
, orsynchronized
. It would be impossible for a class to implement aprivate abstract
method, becauseprivate
methods are not inherited by subclasses; therefore such a method could never be used. - Interfaces may contain member type declarations (nested type). A member type declaration in an interface is implicitly
static
andpublic
. It is permitted to redundantly specify either or both of these modifiers. - The
default
methods are implicitlypublic
— there's no need to specify thepublic
modifier.
Default Methods Use Case —
a. helps minimize code duplication
b. single location to write & edit
c. can be overridden if necessary
d. can be overridden per class precision



5. A static
method can be invoked from other static
or from default
method. A static
method cannot be overridden or changed in the implementation class. The static
methods are implicitly public
— there's no need to specify the public
modifier.
6. The private
methods must contain body. As 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.
Private Methods Use Case — if two default
methods needed to share code, a private
method in the interface would allow them to do so, but without exposing that private
method to interface implementing class.
7. The private static
methods are useful when you have multiple public static
methods that share some common code. A private static
methods can be called from instance (i.e. default
or private
non-static) method or static
method inside the interface. A private
non-static method is not allowed to be called from static
or private static
method within the interface
