This is the 18th day of my participation in the August Genwen Challenge.More challenges in August
FunctionalInterface @functionalinterface
The Runnable example is used in Lambda_01, so why should Runable use Lambda expressions? In JDK1.8, Runable was annotated == @functionalinterface ==
What is a functional interface
Interface == has and only one abstract method == function interface, == more than a compilation error. = =
interface LambdaInterface4{
// Abstract method fun1
public void fun1(a);
// Abstract method fun2
public void fun2(a);
}
Copy the code
Yi? How come the above code does not report an error?
== because the above code is not a functional interface == let’s implement the following
public class Lambda04 {
public static void main(String[] args) {
LambdaInterface4 lambdaInterface4 = new LambdaInterface4() {
@Override
public void fun(a) {}@Override
public void fun2(a) {}}; }}interface LambdaInterface4{
public void fun(a);
public void fun2(a);
}
Copy the code
The above code implements the Java interface, == not the function interface ==, you can try Lambda expressions. It won’t.LambdaInterface4 also cannot be commented out by == @functionalInterface ==. Because there are two abstract methods in the interface.Comment out the fun2 method: perfect solution to the error.
You can have other methods in the @functionalInterface annotation.
@FunctionalInterface
interface LambdaInterface{
// Abstract methods
public void fun(a);
// Methods in java.lang.Object are not abstract methods
public boolean equals(Object var1);
// Default is not an abstract method
public default void defaultMethod(a){}
Static is not an abstract method
public static void staticMethod(a){}}Copy the code
Rules for using @functionalInterface
- There is and only one abstract method
- Static methods and default methods are not abstract methods
- The interface inherits java.lang.Object by default, and the interface display declaration overwrites methods in Object and is not abstract.