JDK8函数式接口Functional Interface

Functional 是什么

函数式接口,首先是一个接口,这个接口里面只能有一个抽象方法。
这种类型的接口也称为SAM接口,即Single Abstract Method interfaces

特点

  • 接口有且仅有一个抽象方法
  • 允许定义静态方法
  • 允许定义默认方法
  • 允许java.lang.Object中的public方法
  • 该注解不是必须的,如果一个接口符合"函数式接口"定义,
    那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。
    如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错

简单例子


@FunctionalInterface
public interface TestInterface {
    int add(int a,int b);
}
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

public class FunctionalInterfaceTest {

    @Test
    public void test1(){
        TestInterface testInterface = (a,b) -> a+b;
        int result = testInterface.add(1,2);
        System.out.println(result);
        
        // 等于如下写法,但是上面看起来更简洁
        TestInterface testInterface1 = new TestInterface() {
            @Override
            public int add(int a, int b) {
                return a+b;
            }
        };
        int result1 = testInterface1.add(1,2);
        System.out.println(result1);
    }
    @Test
    public void test2(){
        Runnable runnable = ()-> System.out.println(111);
        Runnable runnable2 = ()->{
            System.out.println(2222);
            System.out.println(222);
        };
        runnable.run();
        runnable2.run();

    }

}

JDK中的函数式接口举例

java.lang.Runnable,
java.util.Comparator,
java.util.concurrent.Callable
java.util.function包下的接口,如Consumer、Predicate、Supplier等

参考:
https://www.jianshu.com/p/52cdc402fb5d
https://blog.csdn.net/aitangyong/article/details/54137067

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值