What kind of variables/methods defined in an interface in Java 9?


Since Java 9, we able to add private methods and private static methods in an interface. The advantage of using private methods in an interface is to reduce code duplication among default and static methods. For instance, if two or more default methods needed to share some code, a private method can be created for the same and called from each of the default methods.

In Java 9, the following variables/methods have defined in an interface.

  • Constant
  • Abstract method
  • Default method
  • Static method
  • Private method
  • Private Static method

Example

import java.util.*;
import java.util.stream.*;
interface InterfaceTest {
   static void printEvenNumbers() {
      getDataStream().filter(i -> i%2==0).forEach(System.out::println);
   }
   static void printLOddNumbers() {
      getDataStream().filter(i -> i%2!=0).forEach(System.out::println);
   }
   private static Stream<Integer> getDataStream() {       // private static method
      List<Integer> list = Arrays.asList(10, 13, 5, 15, 12, 20, 11, 25, 16);
      return list.stream();
   }
}
public class InterfacePrivateMethodTest implements InterfaceTest {
   public static void main(String args[]) {
      System.out.println("The even numbers: ");
      InterfaceTest.printEvenNumbers();
      System.out.println("The odd numbers: ");
      InterfaceTest.printLOddNumbers();
   }
}

Output

The even numbers:
10
12
20
16
The odd numbers:
13
5
15
11
25

Updated on: 24-Feb-2020

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements