java1.8学习-什么样的匿名内部类能被lambda语法代替?

java1.8学习-什么样的匿名内部类能被lambda语法代替?

java1.8好多新的特性真的很有意思,特别是Lambda。在学习的时候发现并不是所有的匿名内部类都可以用Lambda代替。

lambda表达式用得最多的场合就是替代匿名内部类,而实现Runnable接口是匿名内部类的经典例子。lambda表达式的功能相当强大,用()->就可以代替整个匿名内部类。
请看代码:

@Test
public void oldRunable() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("The old runable now is using!");
        }
    }).start();
}

而如果使用lambda表达式:

@Test
public void runable() {
    new Thread(() -> System.out.println("It's a lambda function!")).start();
}

但问题来了,这个替代匿名内部类的方式并不是所有情况都适合。
翻阅官方文档发现有关Funtional interfaces的说法:

Functional interfaces. The Runnable interface—like the Callable interface, the Comparator interface, and a whole host of other interfaces already defined within Java—is what Java 8 calls a functional interface: it is an interface that requires exactly one method to be implemented in order to satisfy the requirements of the interface. This is how the syntax achieves its brevity, because there is no ambiguity around which method of the interface the lambda is trying to define.

即:Lambda表达式只支持函数式接口。也就是只有一个抽象方法的接口

转载于:https://www.cnblogs.com/virde/p/study_java8_lamdba_innerclass.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值