Java8-函数接口(Functional Interface)

来源:互联网 发布:abb离线编程软件 编辑:程序博客网 时间:2024/05/21 10:31

什么是函数接口


在学习函数接口前我们需要了解下Single Abstract Method interfaces (SAM Interfaces),下面看一个简单的demo:

public class AnonymousInnerClassTest {    public static void main(String[] args) {        new Thread(new Runnable() {            @Override            public void run() {                System.out.println("A thread created and running ...");            }        }).start();    }}

其实在我们Java开发中,会用到很多这样类似的方法,比如:java.lang.Runnable,java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable等等,他们都有一个共同的特点,在这些接口声明里面都只有一个方法。而这些接口就被称作单一抽象方法接口(Single Abstract Method interfaces )。

在Java8中,SAM Interfaces被重建(recreated )为Functional interfaces。多被应用于lambda表达式、方法引用(method reference )以及构造引用(constructor references)。

定义一个函数接口


接下来我们尝试写一个函数接口。

@FunctionalInterfacepublic interface SimpleFuncInterface {    void doSomething();}

需要注意的是,在函数接口中,只能有一个抽象方法,如果声明了两个抽象方法,编译器会报错。
这里写图片描述

函数接口可以被继承,代码如下:

@FunctionalInterfacepublic interface ComplexFunctionalInterface extends SimpleFuncInterface {    default void doWork() {        System.out.println("do work");    }    default void doAnotherWork() {        System.out.println("do another work");    }}

需要注意的是,导出类函数接口不能声明抽象方法,否则编译器会报错。但是导出类函数接口中可以包含多个默认方法。

使用一个函数接口

接下来我们通过一个简单的例子来使用上面的函数接口。

public class Main {    public static void main(String[] args) {        // 匿名内部类调用        carryOut(new SimpleFuncInterface() {            @Override            public void doSomething() {                System.out.println("do something");            }        });        //lambda表达式调用        carryOut(() -> System.out.println("do another thing"));    }    public static void carryOut(SimpleFuncInterface simpleFuncInterface) {        simpleFuncInterface.doSomething();    }}

输出如下:
do something
do another thing

恰当的使用函数接口可以使代码更简洁,并提高可读性。

参考文章地址:https://www.javacodegeeks.com/2013/03/introduction-to-functional-interfaces-a-concept-recreated-in-java-8.html

原创粉丝点击