Java8-函数接口(Functional Interface)

什么是函数接口


在学习函数接口前我们需要了解下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)。

定义一个函数接口


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

@FunctionalInterface
public interface SimpleFuncInterface {
    void doSomething();
}

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

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

@FunctionalInterface
public 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值