void方法可以精简成:
public class tmp {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException {
Dog d = () -> System.out.println("aaa");
d.add();
}
}
interface Dog{
void add();
}
精简4中的代码:
public class tmp {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException {
Dog d = (a,b)->(a + b);
System.out.println(d.add(3, 2));
}
}
interface Dog{
int add(int a, int b);
}
又如:
public class tmp {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException {
Dog d = a-> System.out.println("a" + a);
d.add("1");
}
}
interface Dog{
void add(String a);
}
单个参数可以不带括号,但是多个参数必须带括号。这个要求是Dog接口的方法里只有一个含一个参数的方法,否则会报错
-
一个参数时,()可省略
-
方法体只有一条语句时,{}可省略
-
如果方法体是return,那省略同时return也要省略
-
参数类型可以省略(String a)可以直接变为(a)