Java 中的 SAM 介面有哪些?
只有一個抽象方法的介面被稱為函式式介面,也稱為單一抽象方法介面(SAM 介面)。一個抽象方法表示允許使用預設方法或實現預設可用的抽象方法。SAM 介面的例項為java.lang.Runnable、java.awt.event.ActionListener、 java.util.Comparator 和 java.util.concurrent.Callable。SAM 介面可以使用lambda 表示式或方法 引用進行實作。
語法
@FunctionalInterface public interface Changeable { public void change(T o); }
示例
@FunctionalInterface interface MyInterface { String reverse(String n); } public class LambdaReverseTest { public static void main( String[] args ) { MyInterface myInterface = (str) -> { // Lambda Expression String result = ""; for(int i = str.length()-1; i >= 0 ; i--) result += str.charAt(i); return result; }; System.out.println("The reverse of string is: " + myInterface.reverse("TutorialsPoint")); } }
輸出
The reverse of string is: tnioPslairotuT
廣告