java Lambda表達式

Lambda表達式只能用來簡化僅包含一個public方法的接口的創建

  1. 只能是接口
    否則報:Target type of a lambda conversion must be an interface
  2. 只能有一個public方法
    否則報:Multiple non-overriding abstract methods found xxx
public class Go {
    public static void main(String a[]) {
        //正確示範
        testA((int i, int j) -> {});
        //錯誤示範:Multiple non-overriding abstract methods found xxx;只能有一個public方法
        testB((int i, int j) -> {});
        //錯誤示範:Target type of a lambda conversion must be an interface;只能是接口
        testC((int i, int j) -> {});
    }

    public static void testA(AInterface t) {    }
    public static void testC(CInterface t) {}
    public static void testB(BInterface t) {}


    interface AInterface {
        void xxx(int i, int j);
    }

    interface BInterface {
        void xxx(int i, int j);
        void YYY(int i, int j);
    }

    abstract class CInterface {
        abstract void xxx(int i, int j);
    }
}

雙冒號表達形式

  1. 雙冒號後面必須是靜態方法
    否則報錯:Non-static method cannot be referenced from a static context
  2. 與接口方法參數一樣
  3. 當然接口只能有一個public方法
    否則報錯:AInterface is not a functional interface
  4. 方法與接口的權限可以不一樣
  5. 返回類型:如果接口裏面方法是void,雙冒號後的方法可以任意返回類型,否則要一致
public class Go {
    public static void main(String a[]) {
        //之前的寫法
        testA(new AInterface() {
            @Override
            public void xxx(int i, int j) {
                
            }
        });
        //正確,相對與接口裏面xxx方這是改成靜態和換了個名字
        testA(Go::mydog);
        //正確,加了返回類型和public換成private,也是ok
        testA(Go::mydog2);
        
        //錯誤:Non-static method cannot be referenced from a static context
        testA(Go::mydog3);

        //這樣寫也是ok的。
        AInterface aInterface = Go::mydog;
        testA(aInterface);
    }

    public static void testA(AInterface t) {
        t.xxx(1, 2);
    }


    interface AInterface {
        void xxx(int i, int j);
    }

    public static boolean mydog(int i, int j) {
        System.out.println("mydog" + i + " & " + j);
        return false;
    }


    private static void mydog2(int i, int j) {
        System.out.println("mydo2" + i + " & " + j);
    }

    public void mydog3(int i, int j) {
        System.out.println("mydog3" + i + " & " + j);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章