java遗珠之lambda与方法重载

栏目: Java · 发布时间: 7年前

内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/82807255

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lastsweetop/article/details/82807255

当lambda的目标类型不是很明确时,就需要根据一些特征来判断lambda的目标类型,比较常见的就是在方法重载的时候。

  1. 与接口中的方法名无关,即使不同名,仍会同时匹配到两个接口
public class OverloadLambda {

    interface Runable {
        void run();
    }

    interface Runable2 {
        void run1();
    }


    void methodA(Runable runable) {
        runable.run();
    }

    void methodA(Runable2 runable2) {
        runable2.run1();
    }


    public static void main(String[] args) {
        new OverloadLambda().methodA(() -> System.out.println("methodA"));
    }
}
  1. 与接口中的参数列表有关,当参数列表不一样时就可以知道调用哪个方法,lambda对应哪个接口了
public class OverloadLambda {

    interface Runable {
        void run();
    }

    interface Runable2 {
        void run(int x);
    }


    void methodA(Runable runable) {
        runable.run();
    }

    void methodA(Runable2 runable2) {
        runable2.run(10);
    }


    public static void main(String[] args) {
        new OverloadLambda().methodA(() -> System.out.println("methodA"));

        new OverloadLambda().methodA((x) -> System.out.println("methodA"+x));
    }
}
  1. 重点要注意返回类型不同也可以区分哦,看例子。
public class OverloadLambda {

    interface Runable {
        void run();
    }

    interface Runable2 {
        String run();
    }


    void methodA(Runable runable) {
        runable.run();
    }

    String methodA(Runable2 runable2) {
        return runable2.run();
    }


    public static void main(String[] args) {
        OverloadLambda overloadLambda = new OverloadLambda();

        overloadLambda.methodA(() -> System.out.println("methodA"));

        System.out.println(overloadLambda.methodA(() -> "methodA return string"));
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Coding the Matrix

Coding the Matrix

Philip N. Klein / Newtonian Press / 2013-7-26 / $35.00

An engaging introduction to vectors and matrices and the algorithms that operate on them, intended for the student who knows how to program. Mathematical concepts and computational problems are motiva......一起来看看 《Coding the Matrix》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具