版本1
interface HelloWorld{
String hello(String s);
}
HelloWorld h = String::new;
h.hello("Something");
Run Code Online (Sandbox Code Playgroud)
版本2
interface HelloWorld{
void hello(String s);
}
HelloWorld h = String::new;
h.hello("Something");
Run Code Online (Sandbox Code Playgroud)
版本3
interface HelloWorld{
String hello();
}
HelloWorld h = String::new;
h.hello();
Run Code Online (Sandbox Code Playgroud)
版本4
interface HelloWorld{
void hello();
}
HelloWorld h = String::new;
h.hello();
Run Code Online (Sandbox Code Playgroud)
我已经创建了相同代码的四个版本,但我没有更改HelloWorld h = String::new;
我能够理解的第一个案例,它创建了新的String of String,其值在参数中传递并返回对象.
有些人可以详细说明为什么编译器在其他情况下没有给出任何错误并有一些解释?
在版本1版本2中,您的String::new
方法引用是指类的public String(String original)
构造函数String
.
在Version 3 sand Version 4中,您的String::new
方法引用是指类的public String()
构造函数String
.
函数接口的方法是返回String
还是具有void
返回类型并不重要.无论哪种方式,相关的String::new
方法引用都符合您的接口方法的签名.
也许编写Java 7等价物会使这更容易理解:
版本1:
HelloWorld h = new HelloWorld () {
String getSomething(String s) {
return new String(s);
}
}
Run Code Online (Sandbox Code Playgroud)
版本2:
HelloWorld h = new HelloWorld () {
void getSomething(String s) {
new String(s);
}
}
Run Code Online (Sandbox Code Playgroud)
版本3:
HelloWorld h = new HelloWorld () {
String getSomething() {
return new String();
}
}
Run Code Online (Sandbox Code Playgroud)
第4版:
HelloWorld h = new HelloWorld () {
void getSomething() {
new String();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
82 次 |
最近记录: |