1.lambda表达式

当接口为函数式接口(接口内只有一个方法)时,可以用lamda表达式来创建该接口的对象

函数式接口:
interface A{ void happy(int num); }
创建接口的对象有多种不同的方法:

1)创建外部类实现接口

该类是一个普通类,与其它类不存在嵌套关系
class D13 implements A{ @Override public void happy(int num) {
System.out.println("Method " + num + " Create a new class to implements
interface"); } }
2)创建静态内部类

该类在外部类的内部,且用static修饰
public class D12 { static class D13 implements A{ @Override public void
happy(int num) { System.out.println("Method " + num + " Create a static
internal class to implements interface"); } } }
3)创建局部内部类

该类在另一个类的方法内部
public class D12 { public static void main(String[] args) { class D13
implements A{ @Override public void happy(int num) { System.out.println("Method
" + num + " Create a local internal class to implements interface"); } } A d =
new D13(); d.happy(3); } }
4)创建匿名内部类

直接new 接口并且实现抽象方法,因为这个类是没有名字的,所以叫匿名内部类
public static void main(String[] args) { A d = new A() { @Override public void
happy(int num) { System.out.println("Method " + num + " Create an anonymous
internal class to implements interface"); } }; d.happy(4); }
5)lamda表达式

(参数)-> { 重写的方法的内容 } 

省略了类名,方法名
public static void main(String[] args) { A d = (int num) -> {
System.out.println("Method " + num + " Use lambda expression to implements
interface"); }; d.happy(5); }
当方法内代码只有一行,可以省略{}

可以省略参数类型 (当有多个参数时,是否省略参数类型,需每个参数一致)
public static void main(String[] args) { A d = num ->
System.out.println("Method " + num + " Use lambda expression to implements
interface"); d.happy(5); }

技术
今日推荐
PPT
阅读数 135
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信