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  
    }
}

 

 

 

 

About Author

Author Image
Mohit Jain

Mohit Jain working as backend java developer having knowlege of core java,spring,hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..