简体   繁体   English

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

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

Version 1 版本1

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

Version 2 版本2

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

Version 3 版本3

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

Version 4 版本4

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

I have created four versions of the same code but I didn't change HelloWorld h = String::new; 我已经创建了四个版本的相同代码,但没有更改HelloWorld h = String::new; First case I am able to understand, it creates new Object of String with value passed in the argument and returns the object. 我能够理解的第一种情况,它将创建新的String对象,并在参数中传递值并返回对象。

Can some elaborate it why compiler is not giving any error in other cases with some explanation? 能否解释一下为什么编译器在其他情况下没有给出任何错误并给出一些解释?

In Version 1 sand Version 2, your String::new method reference is referring to the public String(String original) constructor of the String class. 在版本1的沙子版本2中,您的String::new方法引用引用了String类的public String(String original)构造函数。

In Version 3 sand Version 4, your String::new method reference is referring to the public String() constructor of the String class. 在版本3的第4版中,您的String::new方法引用引用了String类的public String()构造函数。

It doesn't matter whether the method of your functional interface returns a String or has a void return type. 函数接口的方法返回String还是具有void返回类型都没有关系。 Either way, the relevant String::new method reference fits the signature of your interface's method. 无论哪种方式,相关的String::new方法引用都适合您接口方法的签名。

Perhaps writing the Java 7 equivalents would make this easier to understand: 也许编写等效的Java 7会使它更容易理解:

Version 1: 版本1:

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

Version 2: 版本2:

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

Version 3: 版本3:

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

Version 4: 版本4:

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

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

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