任何具有单一方法的接口都可以被视为功能接口吗?
Can any interface with a single method, be considered a Functional Interface?
例如我有这个接口:
package tester;
public interface Calculator{
public int calculate(int a,int b);
}
或
package tester;
@FunctionalInterface
public interface Calculator{
public int calculate(int a,int b);
}
我也可以把第一个当作函数式接口。例如:
package tester;
public class A {
int a;
int b;
int sum;
A(Calculator c,int e, int d){
a=e;
b=d;
sum =c.calculate(a, b);
}
int get(){
return sum;
}
}
class 亚军
package tester;
public class runner {
public static void main(String a[]){
System.out.println(new A((x,b)-> (x+b),1,2).get());
}
}
无论有没有注解,代码都可以工作,那为什么要有注解呢?
为什么不能说任何方法单一的接口都可以是函数式接口?
是的,任何具有一个要实现的抽象方法的接口都可以是功能接口,注释 FunctionalInterface
不是必需的,它只是一个 信息性 注释,如javadoc.
An informative annotation type used to indicate that an interface
type declaration is intended to be a functional interface as defined
by the Java Language Specification.
...
However, the compiler will treat any interface meeting the definition
of a functional interface as a functional interface regardless of
whether or not a FunctionalInterface
annotation is present on the
interface declaration.
FunctionalInterface 注释只是对编译器的提示,是的,任何具有一个抽象方法的接口都可以是功能接口。注释可能有助于检测功能界面中的错误。例如:
@FunctionalInterface
public interface ExampleInterface {
}
会导致编译错误。
例如我有这个接口:
package tester;
public interface Calculator{
public int calculate(int a,int b);
}
或
package tester;
@FunctionalInterface
public interface Calculator{
public int calculate(int a,int b);
}
我也可以把第一个当作函数式接口。例如:
package tester;
public class A {
int a;
int b;
int sum;
A(Calculator c,int e, int d){
a=e;
b=d;
sum =c.calculate(a, b);
}
int get(){
return sum;
}
}
class 亚军
package tester;
public class runner {
public static void main(String a[]){
System.out.println(new A((x,b)-> (x+b),1,2).get());
}
}
无论有没有注解,代码都可以工作,那为什么要有注解呢? 为什么不能说任何方法单一的接口都可以是函数式接口?
是的,任何具有一个要实现的抽象方法的接口都可以是功能接口,注释 FunctionalInterface
不是必需的,它只是一个 信息性 注释,如javadoc.
An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.
...
However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a
FunctionalInterface
annotation is present on the interface declaration.
FunctionalInterface 注释只是对编译器的提示,是的,任何具有一个抽象方法的接口都可以是功能接口。注释可能有助于检测功能界面中的错误。例如:
@FunctionalInterface
public interface ExampleInterface {
}
会导致编译错误。