As we know till Java 7, we are not allowed to add any concrete function to the Interface, All the function should be abstract and must be implemented in Child class which is implementing the interface. i.e. an interface can only have
-
Constant variable
-
abstract method
With Java 8, we can add static and
default method as well in an Interface. Check my blog
on Java 8 for more details. So, an Interface now can have
-
Constant Variable
-
Abstract Method
-
Default Method
-
Static Method
and
with Java 9, It become more powerful and now we can add private
method and private static method.
but
why do we need private function in an Interface. Let’s understand
this with an example.
In
above example, we can observe that all the default function has same code
to create database connection (duplicate code) and fetching the data and database
details is also exposed to outside the world.
So over here, Private method will come to rescue. Check below example where the database code reside in one private method which can be easily accessible to all default function in that interface and it is also hidden to the outside world.
These
private methods will improve code re-usability inside interfaces and
will provide choice to expose only our intended methods
implementations to users. These methods are only accessible within
that interface only and cannot be accessed or inherited from an
interface to another interface or class.
Rules
For using Private Methods in Interfaces
-
Private interface method can be static or instance and In both cases, the private method is not inherited by sub-interfaces or implementations.
-
Private interface method cannot be abstract. it will give compiler error.
-
Private method can be used only inside interface and other static and non-static interface methods.
-
Private non-static methods cannot be used inside private static methods.
-
We should use private modifier to define these methods and no lesser accessibility than private modifier.
Java 9 code can be downloaded from GITHUB