繁体   English   中英

Java 8方法签名相同方法的不同版本

[英]Java 8 Method Signature different versions of same method

版本1

interface HelloWorld{
    String hello(String s);
}
HelloWorld h = String::new;
h.hello("Something");

版本2

interface HelloWorld{
    void hello(String s);
}
HelloWorld h = String::new;
h.hello("Something");

版本3

interface HelloWorld{
    String hello();
}
HelloWorld h = String::new;
h.hello();

版本4

 interface HelloWorld{
     void hello();
 }
 HelloWorld h = String::new;
 h.hello();

我已经创建了四个版本的相同代码,但没有更改HelloWorld h = String::new; 我能够理解的第一种情况,它将创建新的String对象,并在参数中传递值并返回对象。

能否解释一下为什么编译器在其他情况下没有给出任何错误并给出一些解释?

在版本1的沙子版本2中,您的String::new方法引用引用了String类的public String(String original)构造函数。

在版本3的第4版中,您的String::new方法引用引用了String类的public String()构造函数。

函数接口的方法返回String还是具有void返回类型都没有关系。 无论哪种方式,相关的String::new方法引用都适合您接口方法的签名。

也许编写等效的Java 7会使它更容易理解:

版本1:

HelloWorld h = new HelloWorld () {
    String getSomething(String s) {
        return new String(s);
    }
}

版本2:

HelloWorld h = new HelloWorld () {
    void getSomething(String s) {
        new String(s);
    }
}

版本3:

HelloWorld h = new HelloWorld () {
    String getSomething() {
        return new String();
    }
}

版本4:

HelloWorld h = new HelloWorld () {
    void getSomething() {
        new String();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM