Lamubda表达式是JDK8开始后的一种新语法形式
作用:简化匿名内部类的代码写法
Lamubda表达式的简化格式
类 变量名=->{
被重写的方法体代码。
}
->是语法形式,没有实际含义
注意:Lamubda表达式只能简化函数式接口的匿名内部类的写法形式
什么是函数接口?
首先必须是接口,其次接口中有且仅有一个抽象方法的形式
通常我们会在接口加上一个@FunctionalInterface
正确形式
@FunctionalInterface
interface Animal {
abstract void run();
}
错误形式
@FunctionalInterface
interface Animal {
abstract void run();
abstract void eat();//报错要求只能有一个抽象方法
}
匿名内部类的普通写发
public class Test1 {
public static void main(String[] args) {
Animal dog=new Animal() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("狗跑的飞快");
}
};
dog.run();
}
}
@FunctionalInterface
interface Animal {
abstract void run();
}
使用Lamubda表达式简化
Animal cat=()-> {
// TODO Auto-generated method stub
System.out.println("猫咪会飞檐走壁");
};
cat.run();
匿名内部类直接作为方法的参数(普通写法)
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
champ(new People() {
@Override
public void act() {
// TODO Auto-generated method stub
System.out.println("老师可以教学生");
}
});
}
public static void champ(People people) {
System.out.println("开始表演");
people.act();
}
}
@FunctionalInterface
interface People{
abstract void act();
}
匿名内部类直接作为方法的参数的简化
package Lamubda;
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//匿名内部类作为方法参数用Lamubda简化
champ(() ->{
// TODO Auto-generated method stub
System.out.println("老师可以教学生");
});
}
public static void champ(People people) {
System.out.println("开始表演");
people.act();
}
}
@FunctionalInterface
interface People{
abstract void act();
}
Lamubda好处
是一个匿名函数,我们可以把Lamubda表达式理解为一段可以传递的代码,它可以写出更简介,更灵活的代码,作为一种更紧凑的代码风格,是java语言表达能力得到提升