JDK8新特性,Lamda简化匿名内部类写法

Lamda表达式:

作用:对匿名内部类的简化。

写法:3种。
(参数) -> 单行语句
(参数) -> { 多行语句 }
(参数) -> 表达式

测试代码:

public class Test05 {
    public static void main(String[] args) {

        // 使用匿名内部类的方式
        m1(new MyInterface1() {
            @Override
            public void method1() {
                System.out.println("method1执行");
            }
        });

        m2(new MyInterface2() {
            @Override
            public void method2(String str) {
                String s = str.toLowerCase();
                System.out.println(s);
            }
        });

        int res1 = m3(new MyInterface3() {
            @Override
            public int method3(int x, int y) {
                return x + y;
            }
        });
        System.out.println(res1);

        // 使用Lamda表达式
        m1(() -> System.out.println("method1执行"));

        m2((str) -> {
            String s = str.toLowerCase();
            System.out.println(s);
        });

        int res2 = m3((x, y) -> 10 + 20);
        System.out.println(res2);
    }

    private static void m1(MyInterface1 inter) {
        inter.method1();
    }

    private static void m2(MyInterface2 inter) {
        inter.method2("HELLO");
    }

    private static int m3(MyInterface3 inter) {
        return inter.method3(10, 20);
    }
}

interface MyInterface1 {
    void method1();
}

interface MyInterface2 {
    void method2(String str);
}

interface MyInterface3 {
    int method3(int x, int y);
}

猜你喜欢

转载自blog.csdn.net/pipizhen_/article/details/107639046