匿名类方式的用法,lambda表达式的用法,方法引用的用法 三者比较

package com.example.demo;

/**
 * @author shenqingwen
 * @date 2020/10/15
 */
public class StudentTest {
    private String name;

    private Integer score;

    //该方法将要注入到函数式接口TestInterface中
    public void setNameAndScore(String name, Integer score)
    {
        this.name = name;
        this.score = score;
        System.out.println("Student "+  name +"'s score is " + score);
    }

    public static void main(String[] args)
    {
        //1.匿名类方式:
//        TestInterface testInterface = new TestInterface(){
//            public void set(StudentTest d, String name, Integer score){
//                d.setNameAndScore(name, score);
//            }
//        };

        //2.lambda表达式的用法:
//        TestInterface testInterface = (studentTest, name, score) -> studentTest.setNameAndScore(name, score);

        //java8方法引用有四种形式:静态方法引用; 构造器引用; 类的任意对象的实例方法引用; 特定对象的实例方法引用;
        //3.类的 任意对象 的实例方法引用的用法:类的任意对象的实例方法引用的语法格式为: 类名::实例方法名
        TestInterface testInterface = StudentTest::setNameAndScore;

        testInterface.set(new StudentTest(), "Alex", 100);
    }

    //表明是函数式接口的注释
    @FunctionalInterface
    interface TestInterface
    {
        // 注意:入参比Student类的setNameAndScore方法多1个Student对象,除第一个外其它入参类型一致
        public void set(StudentTest d, String name, Integer score);
    }

}

 

与下篇博客https://blog.csdn.net/qq_16494249/article/details/109110196

中代码进行对比,可帮助理解 类的任意对象的实例方法引用 与 特定对象的实例方法引用 两者间的区别:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值