简化程序的编写,避免匿名内部类定义过多,其实属于函数式编程的概念。
函数式接口定义:任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。 对于函数式接口,我们可以通过lambda表达式创建该接口的对象。
一般情况下我们实现一个函数式接口都是下面这样的操作
public class TestLambda {
public static void main(String[] args) {
Lam lam = new Lam();
//调用实现方法
lam.lambda();
}
}
//定义函数式接口
interface LamImpl{
void lambda();
}
//接口的实现类
class Lam implements LamImpl{
public void lambda() {
System.out.println("实现类!!!");
}
}
显然这样比较麻烦,我们可以进行简化,使用静态内部类
public class TestLambda {
//静态内部类
static class Lam implements LamImpl{
public void lambda() {
System.out.println("静态内部类");
}
}
public static void main(String[] args) {
Lam lam = new Lam();
//调用实现方法
lam.lambda();
}
}
//定义函数式接口
interface LamImpl{
void lambda();
}
也可以将该类放在方法内,使用局部内部类
public class TestLambda {
public static void main(String[] args) {
//局部内部类
class Lam implements LamImpl{
public void lambda() {
System.out.println("局部内部类");
}
}
Lam lam = new Lam();
//调用实现方法
lam.lambda();
}
}
//定义函数式接口
interface LamImpl{
void lambda();
}
我们可以对局部内部类进行优化,改为匿名内部类
public class TestLambda {
public static void main(String[] args) {
LamImpl lam;
//匿名内部类
lam = new LamImpl() {
public void lambda() {
System.out.println("匿名内部类");
}
};
//调用实现方法
lam.lambda();
}
}
//定义函数式接口
interface LamImpl{
void lambda();
}
最终进化在java8版本后可以使用Lamable表达式进行简化
public class TestLambda {
public static void main(String[] args) {
LamImpl lam;
//匿名内部类
lam = ()->{System.out.println("Lambda表达式");};
//调用实现方法
lam.lambda();
}
}
//定义函数式接口
interface LamImpl{
void lambda();
}
lambda表达式和匿名内部类的区别
所以如果还不熟练lambda表达式的写法可以先写成匿名内部类,然后去掉上图框框中的内容即可。
1、
public class LamdbaTest {
public static void main(String[] args) {
calc c ;
//匿名内部类
c = new calc() {
public int operation(int x, int y) {
return x+y;
}
};
System.out.println(c.operation(1, 2));
}
}
interface calc{
int operation(int x , int y);
}
2、
public class LamdbaTest {
public static void main(String[] args) {
calc c ;
//匿名内部类->Lambda
c = /* new calc() { */
/* public int operation */ (int x, int y)-> {
return x+y;
}
};
System.out.println(c.operation(1, 2));
}
}
interface calc{
int operation(int x , int y);
}
3、
public class LamdbaTest {
public static void main(String[] args) {
calc c;
//lambda表达式
c = (int x, int y)-> {return x+y;};
System.out.println(c.operation(1, 2));
}
}
interface calc{
int operation(int x , int y);
}