λ表达式 · 演变

it2023-01-22  55

使用条件

接口必须是函数式接口。即接口中只有一个抽象方法

lambda演变

外部类 –> 静态内部类 –> 局部内部类 –> 匿名内部类 –> lambda

1、常规接口实现

// lambda表达式演变过程 public class TestLambda { public static void main(String[] args) { ILike like = new Like(); like.lambda(); } } // 定义外部接口 类 // 定义单实现案例 interface ILike{ void lambda(); } class Like implements ILike{ @Override public void lambda() { System.out.println("I like lambda like you !"); } }

I like lambda like you !

2、更改外部类为静态内部类

public class TestLambda { static class Like implements ILike{ @Override public void lambda() { System.out.println("I like lambda like you-静态内部类 !"); } } public static void main(String[] args) { ILike like = new Like(); like.lambda(); } } interface ILike{ void lambda(); }

I like lambda like you-静态内部类 !

3、更改为局部内部类

public class TestLambda { public static void main(String[] args) { class Like implements ILike{ @Override public void lambda() { System.out.println("I like lambda like you--局部内部类 !"); } } ILike like = new Like(); like.lambda(); } } interface ILike{ void lambda(); }

I like lambda like you–局部内部类 !

4、更改为匿名内部类

public class TestLambda { public static void main(String[] args) { ILike like; // 匿名内部类没有名次,借助接口或父类创建 like = new ILike() { @Override public void lambda() { System.out.println("I like lambda like you--匿名内部类 !"); } }; like.lambda(); } } interface ILike{ void lambda(); }

I like lambda like you–匿名内部类 !

5、最终优化

public class TestLambda { public static void main(String[] args) { ILike like; like = ()-> { System.out.println("I like lambda like you--lambda !"); }; like.lambda(); } } interface ILike{ void lambda(); }

I like lambda like you–lambda !

最新回复(0)