正如我们所了解的,在Java 8中,引入了函数式接口的概念。函数式接口有一个abstract
方法,同时也可以拥有多个默认方法或静态方法。
但是为什么函数式接口只能有一个抽象方法呢?如果接口有多个抽象方法,为什么它就不能成为函数式接口呢?
正如我们所了解的,在Java 8中,引入了函数式接口的概念。函数式接口有一个abstract
方法,同时也可以拥有多个默认方法或静态方法。
但是为什么函数式接口只能有一个抽象方法呢?如果接口有多个抽象方法,为什么它就不能成为函数式接口呢?
函数式接口也称为单一抽象方法接口,旨在便于Lambda函数。由于Lambda函数只能为1个方法提供实现,因此函数式接口必须仅有一个抽象方法。更多详情,请参见此处。
编辑 -> 另外值得注意的是,函数式接口可以在接口中具有默认实现。您可以在上述链接中找到更多实现细节。
@FunctionalInterface
interface MyInterface {
void display();
void display(int x, int y);
}
然后如果实施以下内容将不可能。
public class LambdaExpression {
public static void main(String[] args) {
MyInterface ref = () -> System.out.print("It is display from sout");
ref.display(2, 3);
}
}
因为display(int x, int y)没有被实现,所以会导致错误。这就是为什么函数接口是单抽象方法接口的原因。
@FunctionalInterface
interface MyInterface {
void display();
void display(int x, int y);
}
- Vishwa Ratna功能接口让我们可以将一个对象当作函数调用,这样我们可以传递动词(函数)而非名词(对象)来处理程序。功能接口的实现执行一个单一、明确定义的操作,就像任何方法应该做的那样,使用像run、execute、perform、apply或其他通用动词的名称[1]。
@FunctionalInterface
interface Interf {
public void m1();
public void m2();
}//error:-Invalid '@FunctionalInterface' annotation Interf not a functional interface
例2:-
interface Interf {
public void m1();
public void m2();
}
public class abc1 {
public static void main(String args[]) {
interf interf = () -> System.out.println("we impl");
interf.m1();
}
}//incompatible types Interf is not a functional interface
multiple non-overriding abstract methods in interface Interf