赞
踩
函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
函数式接口可以被隐式转换为 lambda 表达式。
Lambda 表达式和方法引用(实际上也可认为是Lambda表达式)上。
@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();
}
我们常用的Runnable接口就是个典型的函数式接口,我们可以看到它有且仅有一个抽象方法run。并且可以看到一个注解@FunctionalInterface,这个注解的作用是强制你的接口只有一个抽象方法。如果有多个话直接会报错,如图:
idea错误提示:


编译时错误提示:

这里当你写了第二个方法时,编译就无法通过,idea甚至在编码阶段就行了提示。
我们直接上代码,首先定义一个函数式接口
@FunctionalInterface
public interface SingleAbstraMethodInterface {
public abstract void singleMethod();
}
我们定一个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("执行函数式接口定义方法");
}
});
}
}
执行结果:
即将执行函数式接口外部定义方法
执行函数式接口定义方法
是不是和我们预期结果一样。这个过程是不是有的同学已经发现,怎么这么像jdk里面的一些接口的使用,比如常用的Runnable接口。我们来看看代码。
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("run方法执行了");
}
}).start();
}
再看下Runnable接口源码,是不是一样
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。