为什么使用Lambda表达式
- 避免匿名内部类定义过多
- 可以让代码看起来简洁
- 去掉没有意义的代码,只留下核心的逻辑
*理解Funtional Interface(函数式接口) 是学习java8 lambda表达式的关键
函数式接口的定义
- 任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。
简化过程:
public class TicketBuyer {
//2.静态内部类
static class TicketBuyerImpl2 implements ITicketBuyer{
@Override
public void test() {
System.out.println("test2");
}
}
public static void main(String[] args) {
//2.局部内部类
class TicketBuyerImpl3 implements ITicketBuyer{
@Override
public void test() {
System.out.println("test3");
}
}
//1.外部类
ITicketBuyer ticketBuyer = new TicketBuyerImpl();
ticketBuyer.test();
//2.静态内部类
ticketBuyer=new TicketBuyerImpl2();
ticketBuyer.test();
//3.局部内部类
ticketBuyer=new TicketBuyerImpl3();
ticketBuyer.test();
//4.匿名内部类
ticketBuyer=new ITicketBuyer(){
@Override
public void test() {
System.out.println("test4");
}
};
ticketBuyer.test();
//5.用lambda简化
ticketBuyer=()->{
System.out.println("test5");
};
ticketBuyer.test();
}
}
//只有一个抽象方法的接口
interface ITicketBuyer{
void test();
}
//1.外部类
class TicketBuyerImpl implements ITicketBuyer{
@Override
public void test() {
System.out.println("test1");
}
}