From Java 9 onwards, we can declare private methods in interface.
In this post I will show with an example of how to do it.
Private methods in interface are useful if you have logic shared by more than one default interface methods. We can put the shared logic in the private method.
Below is the complete code.
IExample interface
package code;
interface IExample {
default public void defaultFunction1() {
this.function("Function1");
}
default public void defaultFunction2() {
this.function("Function2");
}
private void function(String variable) {
System.out.println("Hello from " + variable);
}
}
In the above code, I have created two public default methods “defaultFunction1” and “defaultFunction2” which call the private method “function”.
The method “function” will take a String values as argument to generate a String of the format “Hello from ‘variable name'”.
In the below main class, I will show how to use the above interface “IExample”.
Main Class
1 package core;
2
3 public class Example1 implements IExample {
4 public static void main(String[] args) {
5 Example1 example1 = new Example1();
6 example1.defaultFunction1();
7 example1.defaultFunction2();
8 }
9 }
In the above code, the class Example1 implements the interface IExample at line 3.
At line 5, we create an instance of Example1.
At line 6 and 7, we call the interface default methods “defaultFunction1” and “defaultFunction2” resulting in the below output
Output
Hello from Function1
Hello from Function2