Java 9 - Private Methods in Interface


java 9, you will most likely include private techniques and private static strategy in interfaces.

Using private techniques in interfaces have four tenets :

  1. Private interface strategy can't be abstract.
  2. Private strategy can be utilized just inside interface.
  3. Private static technique can be utilized inside other static and non-static interface methods.
  4. Private non-static strategies can't be utilized inside private static techniques

    Java 9 Private Interface Method Example

    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




    javacodegeeks is optimized for learning.© javacodegeeks .
    All Right Reserved and you agree to have read and accepted our term and condition