Consider following interface.
interface Runnable{
public void run();
}
Which of the following will create instance of Runnable type?
A.
Runnable run = () -> {System.out.println("Run");};
B.
Runnable run = () -> System.out.println("Run");
C.
Runnable run = () > System.out.println("Run");
D.
Runnable run = > System.out.println("Run");
E. None of the above.
题解
Java 8 导入了 Lambda 语法,可以参考这篇文章来学习:
选项 A 是完整的 Lambda 语法,为正确答案。以这里列出的程序来看,选项 B 只是省略了大括号,也是合法的 Lambda 语法,实际上同样可以通过编译并创建出 Runnable 的实体。不过这题只能选择一个答案,选择选项 A 的话会比较合适。选项 C 和选项 D 都没有使用「->」,会编译错误。