Java>方法引用

用到的接口
.

public interface Method_interface_01 {
    // absolutely
    int calc(Integer integer);
}

方法引用

public class Method_print {
    // 方法引用 重写 Method_interface_01 接口内的方法
    public static void method_math(Method_interface_01 me, String num) {
        // 这里只是起到了一个将num形参变量传入calc方法中,但是此刻并没有完全传入calc方法,
        // calc 方法并没有完全意义上重写,此时num形参,只是传入了parseInt方法中,首先进行了转换
        // 然后将值传入calc
        System.out.println(me.calc(Integer.parseInt(num)));
    }

    public static void main(String[] args) {
        // 原本的   方法重写
        method_math(new Method_interface_01(){
            @Override
            public int calc(Integer integer) {
                return Math.abs(integer);
            }
        },"120");
        // 这里'120'字符串数字,将字符传入方法内时
        // 首先进入的不是Method_interface_01接口内的calc方法, 而是先进入Integer下的parseInt方法内
        // 将String num转换为Integer类型之后,才会进入calc方法内,重写的方法进行绝对值的计算

        // lambda 表达式 1 初始写法
        method_math(s -> {
            return Math.abs(s);
        },"110");

        // lambda 表达式 2 简化版本
        method_math(s-> Math.abs(s),"100");

        // lambda 优化之后 2 方法引用版本
        method_math(Math::abs, "89");
    }
}
方法引用的前提条件
1、需要用的方法引用的类中,必须有现成的放方法
2、方法中,传入的接口的返回值,必须与引用的方法的接受的值相同
	如:num形参传入calc方法中时间,必须经过parseInt转换为Integer类型,方法重写之后,
	才能进入进入calc方法中,执行代码块Math.abs(int num)

日记类博客,如有差错,欢迎讨论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值