java Lambda表达式心得

###java Lambda表达式只能用来简化仅包含一个public方法的接口的创建

规则

  1. 只能是接口
    否则报:Target type of a lambda conversion must be an interface
  2. 只能有一个public方法
    否则报:Multiple non-overriding abstract methods found AInterface
    或AInterface is not a functional interface
括号形式
  1. testA((int i, int j) -> {});参数要与接口一致
public class Go {
    public static void main(String a[]) {
        //正确示范
        testA((int i, int j) -> {});
        //错误示范:Multiple non-overriding abstract methods found xxx;只能有一个public方法
        testB((int i, int j) -> {});
        //错误示范:Target type of a lambda conversion must be an interface;只能是接口
        testC((int i, int j) -> {});
    }

    public static void testA(AInterface t) {    }
    public static void testC(CInterface t) {}
    public static void testB(BInterface t) {}


    interface AInterface {
        void xxx(int i, int j);
    }

    interface BInterface {
        void xxx(int i, int j);
        void YYY(int i, int j);
    }

    abstract class CInterface {
        abstract void xxx(int i, int j);
    }
}

#####双冒号表达形式

  1. 双冒号后面必须是静态方法
    否则报错:Non-static method cannot be referenced from a static context
  2. 双冒号后面的方法与接口方法参数一样
  3. 方法与接口的权限可以不一样
  4. 返回类型:如果接口里面方法是void,双冒号后的方法可以任意返回类型,否则要一致
public class Go {
    public static void main(String a[]) {
        //之前的写法
        testA(new AInterface() {
            @Override
            public void xxx(int i, int j) {
                
            }
        });
        //正确,相对与接口里面xxx方这是改成静态和换了个名字
        testA(Go::mydog);
        //正确,加了返回类型和public换成private,也是ok
        testA(Go::mydog2);
        
        //错误:Non-static method cannot be referenced from a static context
        testA(Go::mydog3);

        //这样写也是ok的。
        AInterface aInterface = Go::mydog;
        testA(aInterface);
    }

    public static void testA(AInterface t) {
        t.xxx(1, 2);
    }


    interface AInterface {
        void xxx(int i, int j);
    }

    public static boolean mydog(int i, int j) {
        System.out.println("mydog" + i + " & " + j);
        return false;
    }


    private static void mydog2(int i, int j) {
        System.out.println("mydo2" + i + " & " + j);
    }

    public void mydog3(int i, int j) {
        System.out.println("mydog3" + i + " & " + j);
    }
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值