避免匿名内部类定义过多
是函数式编程的概念
package com.kai.lesson2;
//推导lambda表达式
public class TestLambda1 {
//3.静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda2");
}
}
public static void main(String[] args) {
ILike like=new Like();
like.lambda();
like=new Like2();
like.lambda();
//4.局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda3");
}
}
like=new Like3();
like.lambda();
//5.匿名内部类,没有类的名称,必须借助接口或者父类
like=new Like(){
@Override
public void lambda() {
System.out.println("i like lambda4");
}
};
like.lambda();
//6.用lambda简化
like = () ->{
System.out.println("i like lambda5");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda");
}
}
例子
package com.kai.lesson2;
public class TestLambda2 {
static class Love2 implements ILove{
@Override
public void love(int a) {
System.out.println("I Lobe U"+a);
}
}
public static void main(String[] args) {
ILove love= new Love();
love.love(1);
love=new Love2();
love.love(2);
class Love3 implements ILove{
@Override
public void love(int a) {
System.out.println("I Lobe U"+a);
}
}
love=new Love3();
love.love(3);
love=new Love(){
@Override
public void love(int a) {
super.love(a);
}
};
love.love(4);
love=(int a)->{
System.out.println("I Lobe U"+a);
};
love.love(5);
//简化
love=a->{
System.out.println("I Lobe U"+a);
};
love.love(6);
}
}
interface ILove{
void love(int a);
}
class Love implements ILove{
@Override
public void love(int a) {
System.out.println("I Lobe U"+a);
}
}
- lambda表达式只能有一行代码的情况下才能简化为1行,否则要用{}包裹
- 必须是函数式接口
- 多个参数也可以去掉参数类型,要去掉都去掉