简体   繁体   中英

Java 8 Method Signature different versions of same method

Version 1

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

Version 2

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

Version 3

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

Version 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; First case I am able to understand, it creates new Object of String with value passed in the argument and returns the object.

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.

In Version 3 sand Version 4, your String::new method reference is referring to the public String() constructor of the String class.

It doesn't matter whether the method of your functional interface returns a String or has a void return type. Either way, the relevant String::new method reference fits the signature of your interface's method.

Perhaps writing the Java 7 equivalents would make this easier to understand:

Version 1:

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

Version 2:

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

Version 3:

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

Version 4:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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