Java8六大新特性之二三 函数式接口函数默认方法和静态方法

本文介绍了Java8中的函数式接口,强调了接口中可以包含一个抽象方法、默认方法和静态方法,并通过@FunctionalInterface注解。内容包括自定义函数式接口的示例,以及java.util.function包中的Consumer、Supplier、Predicate和Function等常见函数式接口的使用案例,展示了它们在处理不同类型操作中的应用。
摘要由CSDN通过智能技术生成

函数式接口介绍

函数式接口中可以且只能有一个抽象方法,还可以有默认方法和静态方法,必须有@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包里面

function包里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值