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)

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

猜你喜欢

转载自blog.csdn.net/weixin_43309893/article/details/116325241