Home >Java >javaTutorial >In Java 9, what types of variables/methods are defined in interfaces?
Starting from Java 9, we can add privatemethods and privatestaticMethods in the interface. The advantage of using private methods in an interface is to reduce code duplication between default and static methods. For example, if two or more default methods need to share some code, you can create a private method for it and call it from each default method.
In Java 9, the following variables/methods have been defined in the interface.
import java.util.*; import java.util.stream.*; interface InterfaceTest { static void printEvenNumbers() { getDataStream().<strong>filter</strong>(i -> i%2==0).<strong>forEach</strong>(System.out::println); } static void printLOddNumbers() { getDataStream().<strong>filter</strong>(i -> i%2!=0).<strong>forEach</strong>(System.out::println); } <strong>private </strong><strong>static </strong>Stream<Integer> getDataStream() { <strong>// private static method</strong> <strong>List<Integer></strong> 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.<strong>printEvenNumbers()</strong>; System.out.println("The odd numbers: "); InterfaceTest.<strong>printLOddNumbers()</strong>; } }
<strong>The even numbers: 10 12 20 16 The odd numbers: 13 5 15 11 25</strong>
The above is the detailed content of In Java 9, what types of variables/methods are defined in interfaces?. For more information, please follow other related articles on the PHP Chinese website!