当前位置:   article > 正文

Java8之函数式接口及常用函数式接口_jdk8函数式接口

jdk8函数式接口

函数式接口

1.概念

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
函数式接口可以被隐式转换为 lambda 表达式。
Lambda 表达式和方法引用(实际上也可认为是Lambda表达式)上。

2.@FunctionalInterface

@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();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

我们常用的Runnable接口就是个典型的函数式接口,我们可以看到它有且仅有一个抽象方法run。并且可以看到一个注解@FunctionalInterface,这个注解的作用是强制你的接口只有一个抽象方法。如果有多个话直接会报错,如图:
idea错误提示:
在这里插入图片描述
在这里插入图片描述
编译时错误提示:
在这里插入图片描述
这里当你写了第二个方法时,编译就无法通过,idea甚至在编码阶段就行了提示。

3.函数式接口使用方式

我们直接上代码,首先定义一个函数式接口

@FunctionalInterface
public interface SingleAbstraMethodInterface {
    public abstract void singleMethod();
}
  • 1
  • 2
  • 3
  • 4

我们定一个test类,封装一个方法,将SingleAbstraMethodInterface当做参数传入方法,并打印一句话

public class Test {
    public void testMethod(SingleAbstraMethodInterface single){
        System.out.println("即将执行函数式接口外部定义方法");
        single.singleMethod();
    }
    public static void main(String[] args) {
        Test test = new Test();
        test.testMethod(new SingleAbstraMethodInterface() {
            @Override
            public void singleMethod() {
                System.out.println("执行函数式接口定义方法");
            }
        });
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

执行结果:

即将执行函数式接口外部定义方法
执行函数式接口定义方法

是不是和我们预期结果一样。这个过程是不是有的同学已经发现,怎么这么像jdk里面的一些接口的使用,比如常用的Runnable接口。我们来看看代码。

public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("run方法执行了");
            }
        }).start();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

再看下Runnable接口源码,是不是一样

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53251
推荐阅读
相关标签