- Private methods can be used on interface from java 9.
- This will help in
- Avoiding code duplication.
- Ensuring code re-usability.
- Improving code readability.
There is a possibility of writing common code on more than one default methods, which leads to code duplication. Introduction of private methods will avoid this code duplication.
Example: On java 8 - Default methods with duplication code.
In the below example, we can see common code is used on both the default methods M1 and M2.
public interface intra {
default void m1() {
//Business code for M1
// common code
}
default void m2() {
//Business code for M2
//common code
}
}
Example: From Java 9 - Default methods with Private method.
In the below example, Common code is extracted and added as a private method which can be called by default methods.
public interface intra {
default void m1() {
//Business code for M1
Common ();
}
default void m2() {
//Business code for M2
Common ();
}
private void common () {
//Common code
}
}