1. 程式人生 > 實用技巧 >Java基礎14-從外部類到lambda

Java基礎14-從外部類到lambda

記載從外部類到靜態內部類、區域性內部類、匿名內部類最後到lambda的簡化過程。
函式式介面:函式式介面(Functional Interface)就是一個有且僅有一個抽象方法,但是可以有多個非抽象方法的介面。(非抽象方法需要default關鍵字)


// 1. 定義函式式介面
interface SayLambda{
    void sayLambda();
}

// 2.外部類
class Say1 implements SayLambda{

    @Override
    public void sayLambda() {
        System.out.println("外部類!");
    }
}

public class TestLambda {
    static class Say2 implements SayLambda{
        @Override
        public void sayLambda() {
            System.out.println("靜態內部類!");
        }
    }

    public static void main(String[] args) {
        Say1 say1 = new Say1();
        say1.sayLambda();

        Say2 say2 = new Say2();
        say2.sayLambda();

        class Say3 implements SayLambda{
            @Override
            public void sayLambda() {
                System.out.println("區域性內部類!");
            }
        }
        Say3 say3 = new Say3();
        say3.sayLambda();

        SayLambda say4 = new SayLambda() {
            @Override
            public void sayLambda() {
                System.out.println("匿名內部類!");
            }
        };
        say4.sayLambda();

        SayLambda say5 = ()->{
            System.out.println("lambda!");
        };
        say5.sayLambda();
    }

}

對lambda的簡化

interface SaySomethingElse{
    void saySomething(int a);
}
public class TestLambda {
    static class Say2 implements SayLambda{
        @Override
        public void sayLambda() {
            System.out.println("靜態內部類!");
        }
    }

    public static void main(String[] args) {
        //對lambda的簡化
        // 簡化前
        SaySomethingElse saySomethingElse = (int a)->{
            System.out.println("Something else "+ a);
        };
        saySomethingElse.saySomething(10);
//        去掉引數型別,去掉括號,去掉花括號
        saySomethingElse = a ->             System.out.println("Something else "+ a);
        saySomethingElse.saySomething(10);
    }

}