Java 8 functional interface
Let's move on to the Java 8 functional programming model
This program is very simple. First initialize a collection of integer types, and then output each element to the console. We notice the foreach method, which is the new default method added in Java 8.
It is declared in the Iterable interface and decorated with the keyword default. In this way, any subtype of the interface can inherit the implementation of the foreach method, so the list interface also inherits the default method because it is an indirect sub interface of Iterable. In this ingenious way, Java 8 not only extends the functions of the interface, but also is compatible with the old version.
Next, analyze the implementation of foreach. First, receive a parameter action of consumer type, judge whether it is not empty, and then traverse all current elements to be processed by the accept method of action. So what the hell is consumer? Look at the source code
An interface with only one abstract method is modified by @ functionalinterface, which is a typical functional interface.
OK, now we know that the parameter of consumer type received by foreach is a functional interface. The only accept abstract method in the interface receives a parameter and does not return a value. As we know from the last article, one way to create instances of functional interface types is to use lambda expressions, so you can modify the top program
The lambda expression item - > system out. Println (item) receives a parameter and does not return a value. It meets the signature requirements of the accept method and has been compiled. That is, if a lambda expression is used to create a functional interface instance, the input and return of the lambda expression must conform to the method signature of the only abstract method in the functional interface.
Next, modify the program
I saw two colons behind out. Anyway, I was messy at that time... This is the second way to create a functional interface instance: method reference. The syntax of method reference is object:: method name
Similarly, the definition of method signature must be followed when using method reference to create functional interface instances. See the println method source code here
Receive a parameter without returning a value and compile it.
Finally, let's look at the last way to create a functional interface. The third way: construct a method reference and continue to change the program
The syntax referenced by the constructor is: Class Name:: new
We added a new constructor to test1. The constructor receives a parameter without returning a value and compiles it. (only to show the usage of constructor reference)
In combination with the previous article, we can summarize three ways to create functional interface types:
1. Lambda expression
2. Method reference
3. Construction method reference
Note: either way, it must conform to the method signature of the abstract method