[英]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.