Home  >  Article  >  Java  >  In Java 9, what types of variables/methods are defined in interfaces?

In Java 9, what types of variables/methods are defined in interfaces?

WBOY
WBOYforward
2023-09-06 13:05:02644browse

在Java 9中,接口中定义了哪些类型的变量/方法?

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.

  • Constant
  • Abstract method li>
  • Default method
  • Static method
  • Private method
  • Private static Method

Example

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

Output

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

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete