函数式接口介绍
函数式接口中可以且只能有一个抽象方法,还可以有默认方法和静态方法,必须有@FunctionalInterface作为注解。
在java里面,lambda表达式需要函数是接口的承载,要不然没法实现。
下面自定义一个函数式接口的例子:
定义函数式接口TestFunInterface
@FunctionalInterface
public interface TestFunInterface{
public void test(); //可以有唯一一个抽象方法
default String getName() { return "Allen"; } //可以有默认方法
static String getGender() { return "Male"; } //可以有静态方法
}
使用该函数式接口TestFunInterface
class TestFunInterfaceImpl implements TestFunInterface {
@Override
public void test() {
System.out.println( "test:" + getName());
}
}
public class FuncInterfaceTest {
public static void test(TestFunInterface tester){
tester.test();
}
public static void main(String[] args) {
// 1. 传入实例
TestFunInterfaceImpl tester = new TestFunInterfaceImpl();
test(tester);
// 2. 传入内部类
test(new TestFunInterface(){
@Override
public void test() {
System.out.println( "test:" + getName());
}
});
//3. Lamadba表达式代替内部类
test(()->System.out.println( "test:"));
}
}
@FunctionalInterface对应的内容在java.lang.util.function包里面