The Java function interface

Functional Interface

First, the concept

  Function interface in java means: one and only one method of abstract interfaces.

  Function interface, i.e. an interface suitable functional programming scenarios. And Java in functional programming is reflected Lambda , so the function interface that can be applied to Lambda -use interface. Only by ensuring the interface and only one abstract method, the Java in Lambda can be deduced smoothly.

  Tips : " syntactic sugar " refers to the use of more convenient, but the principle is the same code syntax. For example, when traversing a collection for-each syntax, in fact achieve the underlying principle remains the iterator, this is " syntactic sugar " . From the application level is concerned, the Java in the Lambda can be taken as an anonymous inner
class " syntactic sugar " , but both are different in principle.

Second, the format

  Just make sure the interface and only one abstract method can be.

  Syntax:

Modifier interface name { 
    public abstract method return type name (optional parameter information); 
    // other non-abstract methods content 
}

    Since the interfaces among the public abstract method of the abstract may be omitted, so that the definition of the function interface is very simple:

public interface MyFunctionalInterface {
    void myMethod();
}

Three, @ FunctionalInterface comment

  And notes the role of @Override similar, Java8 specialized in the introduction of a new annotated functional interfaces: @FunctionalInterface.

  The annotation can be used for defining an interface:

@FunctionalInterface
public interface MyFunctionalInterface {
    void myMethod();
}

  By using this annotation to define interfaces, the compiler will be forced to check whether the interface does have one and only one abstract method, otherwise it will error.

  Note that, even without the application of the notes, as long as the definition of functional interface, which is still a function interface, use all the same.

Fourth, the custom function interface

  For just defined MyFunctionInterface function interface, a typical scenario is used as a parameter of the method:

. 1  public  class DemoFunctionalInterface {
 2          // use the self-function interface as defined in method parameters 
. 3          Private  static  void doSomething (Inter MyFunctionalInterface) {
 . 4              inter.myMethod (); // call the function interface custom method 
. 5          }
 . 6  
. 7          public  static  void main (String [] args) {
 . 8              // call the function to use the interface 
. 9              doSomething (() -> System.out.println ( "the Lambda execute it!" ));
 10          }
 11      }

 

Guess you like

Origin www.cnblogs.com/niujifei/p/11614081.html