Java 9 private methods now applicable in interface
Posted By : Mohit Jain | 23-Sep-2018
Loop holes in Java 8 "default" and "static" method of an interface:-
1.) We can't modularize both methods if the length of logic(code) is big.
2.) We can't reuse the LOC(line of code ) which may be repeating in the same default and static methods.
3.)No data reusability between 2 methods.
Note:1- We consider our all examples here only for one case i.e "default" method which clarify point (3.) same concept is applicable for "static" method also.
For example:-
interface Java8Interface{
default void defaultMethod1() {
System.out.println("Starting method");//common
System.out.println("Prepare some data");//common
System.out.println("Operation 1");
}
default void defaultMethod2() {
System.out.println("Starting method");//common
System.out.println("Prepare some data");//common
System.out.println("Operation 2");
}
}
Although, we can achieve this by making another intermediate "default" and "static" methods which don't make any sense because that intermediate logic is never required by the implementation classes. so, we need to hide that logic which is never gone to be used by implementation classes. Unfortunately, in java 8 we can't have alternative for this.
For example:-
interface Java8Interface{
default void defaultMethod1() {
System.out.println("Operation 1");
}
default void defaultMethod2() {
System.out.println("Operation 2");
}
default void common()//reusiblity(but does not make sense) because never used by implementation classes
{
System.out.println("Starting method");//common
System.out.println("Prepare some data");//common
}
}
Java 9 allows "private" methods(static or non-static) inside interface's to improve above loop holes:-
Note:-2 "abstract" methods must not be "private"
For example:-
interface Java9Interface{
default void defaultMethod1() {
common();
System.out.println("Operation 1");
}
default void defaultMethod2() {
common();
System.out.println("Operation 2");
}
private void common()//reusiblity(Valid)
{
System.out.println("Starting method");//common
System.out.println("Prepare some data");//common
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Mohit Jain
Mohit Jain working as backend java developer having knowlege of core java,spring,hibernate.