Create thread
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("我是一个线程哦");
}
}).start();
lambda creates thread
new Thread(() -> System.out.println("我是一个线程哦")).start();
Lambda implements abstract methods
Precautions:
- There is one and only one abstract method in the implementation interface of lambda; the
context must be available to derive the interface corresponding to the lambda.
public interface Eat {
int eat(int a,int b);
}
Omission method:
- The parameter type can be omitted. In the case of multiple parameters, only one cannot be omitted;
- When there is only one parameter, the parentheses can be omitted;
- When there is only one method body or code block, braces, semicolons, and return can all be omitted.
Define a method, pass the formal parameters into the interface, the method body rewrites the method of the interface, and then the main method calls the lambda style
TestEat((int a, int b) -> {
return a + b;
});
}
//----------省略过后-----------------
TestEat((a, b) ->
a + b
);
//-----------------------------------
public static void TestEat(Eat e) {
int i = e.eat(10, 20);
System.out.println(i);//30
}
The difference between lambda and anonymous inner class
// 接口中有两个方法,直接报错
TestEat((a, b) ->
a + b
);
// 接口中有两个方法,匿名内部类可以使用
TestEat(new Eat() {
@Override
public int eat(int a, int b) {
return a+b;
}
@Override
public void method() {
System.out.println("匿名内部类新增的方法");
}
});
}
//-----------------------------------
public static void TestEat(Eat e) {
int i = e.eat(10, 20);
System.out.println(i);
}
}