Java 8中的Functional Interface有什么用? [英] What is use of Functional Interface in Java 8?

查看:2310
本文介绍了Java 8中的Functional Interface有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java 8中遇到了一个名为功能接口的新术语。

I came across a new term named Functional Interface in Java 8.

我只能在使用时找到此接口的一个用途 lambda表达式

I could only find one use of this interface while working with lambda expressions.

Java 8提供了一些内置的功能接口,如果我们想要定义任何功能接口,那么我们可以使用 @FunctionalInterface 注释。它允许我们在界面中只声明一个方法。

Java 8 provides some built-in functional interfaces and if we want to define any functional interface then we can make use of the @FunctionalInterface annotation. It will allow us to declare only a single method in the interface.

例如:

@FunctionalInterface
interface MathOperation {
    int operation(int a, int b);
}

除了使用 lambda之外,它在Java 8中的用处有多大表达式

问题这里与我提出的不同。它在使用Lambda表达式时询问为什么我们需要功能接口。我的问题是:为什么使用功能接口而不是直接使用 lambda表达式

The question here is different from the one I asked. It is asking why we need Functional Interface while working with Lambda expression. My question is: why using Functional Interface other than directly with lambda expressions?

推荐答案

@FunctionalInterface 注释对于代码的编译时间检查很有用。除了 static default 以及覆盖中的方法的抽象方法之外,您不能有多个方法您的 @FunctionalInterface 中的对象或用作功能界面的任何其他界面。

@FunctionalInterface annotation is useful for compilation time checking of your code. You cannot have more than one method besides static, default and abstract methods that override methods in Object in your @FunctionalInterface or any other interface used as a functional interface.

但是你可以在没有这个注释的情况下使用lambdas,也可以在没有 @Override 注释的情况下覆盖方法。

But you can use lambdas without this annotation as well as you can override methods without @Override annotation.

来自docs


功能界面只有一个抽象方法。由于默认的
方法有一个实现,因此它们不是抽象的。如果接口
声明一个覆盖
java.lang.Object的公共方法之一的抽象方法,那么它也不会计入接口的
抽象方法计数,因为接口的任何实现都将
有来自java.lang.Object或其他地方的实现

a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere

这个可用于 lambda表达式:

This can be used in lambda expression:

public interface Foo {
  public void doSomething();
}

lambda表达式中无法使用

This cannot be used in lambda expression:

public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}

但这会产生编译错误

@FunctionalInterface
public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}




@FunctionalInterface注释无效; Foo不是功能性的
界面

Invalid '@FunctionalInterface' annotation; Foo is not a functional interface

这篇关于Java 8中的Functional Interface有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆