Java 9 Private Method in Interface Example

Since java 9, we can able to add private methods and private static methods in interfaces.
These private methods will improve code re-usability inside interfaces. For example, if two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method to it’s implementing classes.
Using private methods in interfaces have four rules :
  • The private interface method cannot be abstract.
  • A private method can be used only inside interface.
  • A private static method can be used inside other static and non-static interface methods.
  • A private non-static method cannot be used inside private static methods.

Java 9 - Private Methods in Interface

CustomCalculator.java – Interface

import java.util.function.IntPredicate;
import java.util.stream.IntStream;
 
public interface CustomCalculator 
{
    default int addEvenNumbers(int... nums) {
        return add(n -> n % 2 == 0, nums);
    }
 
    default int addOddNumbers(int... nums) {
        return add(n -> n % 2 != 0, nums);
    }
 
    private int add(IntPredicate predicate, int... nums) { 
        return IntStream.of(nums)
                .filter(predicate)
                .sum();
    }
}

Main.java – Class

public class Main implements CustomCalculator {
 
    public static void main(String[] args) {
        CustomCalculator demo = new Main();
         
        int sumOfEvens = demo.addEvenNumbers(1,2,3,4,5,6,7,8,9);
        System.out.println(sumOfEvens);
         
        int sumOfOdds = demo.addOddNumbers(1,2,3,4,5,6,7,8,9);
        System.out.println(sumOfOdds);
    } 
}
Output:
20
25

References


Comments