Java8 functional interface

What is a functional interface

Functional interfaces, also known as single abstract method interfaces (SAM interfaces), are a new addition to java8 that allows you to use only one abstract method

In java8, functional interfaces can be represented using lambda expressions, method references, and constructor references

Java8 also introduced an annotation,@functionalinterface, that causes a compilation error when you annotate an interface that violates the contract of an abstract method.

Let’s build our first functional interface

@FunctionalInterface
public interface MyFirstFunctionalInterface 
{
    public void firstWork(a);
}

Copy the code

When we add another abstract method to this interface, we will cause a compilation error

@FunctionalInterface
public interface MyFirstFunctionalInterface {

	public void firstWork(a);

	public void secendWork(a);
}
Copy the code

Error message: multiple non – overriding abstract ` ` the methods found in interface ` ` MyFirstFunctionalInterface

The IDEA editor we used will directly report an error indicating that there are multiple methods in the interface that have not been overridden

2 Precautions in functional interfaces

  • Only one abstract method is allowed in a functional interface, and the second is not allowed if we remove it@FunctionalInterfaceThis annotation, and then we can add an abstract method, but the interface is no longer functional,
  • when@FunctionalInterfaceIf the interface conforms to the functional interface specification, the interface is still valid. It simply tells the compiler to execute a single abstract method within the interface
  • In theory, a functional interface has only one abstract method, and the default method has its own implementation. Since the default method is not abstract, you are free to add a default method to your own functional interface.

Here is an example of a functional interface that works

@FunctionalInterface
public interface MyFirstFunctionalInterface 
{
    // Abstract methods
    public void firstWork(a);
 
    default void doSomeMoreWork1(a){
    //Method body
    }
 
    default void doSomeMoreWork2(a){
    //Method body}}Copy the code

This method has an abstract method and two default methods, each of which has its own implementation,

  • If an interface declares an abstract method that overrides a public method in a java.lang.Object method, that method is not counted in the count of abstract methods.

    @FunctionalInterface
    public interface Comparator<T> {
    int compare(T o1, T o2);
    
    boolean equals(Object obj); . }Copy the code

    Compare and equals are two abstract methods, but since equals is an Object method, it is not counted in this interface abstract method.