interface HelloWorld {
String hello(String s);
}
public static void main(String[] args) {
HelloWorld h = String::new;
System.out.println(h.hello("dasdasdadasd"));
}
Run Code Online (Sandbox Code Playgroud)
当我执行上面的方法时,它返回我在参数dasdasdadasd中传递的值. 执行字符串类的哪个方法,或者是java在运行时提供的默认实现,或者默认情况下它调用supplier.get()方法?
版本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,其值在参数中传递并返回对象.
有些人可以详细说明为什么编译器在其他情况下没有给出任何错误并有一些解释?