在Java中使用@FunctionalInterface註解標記函式式介面是否強制性的?


僅定義了一個抽象方法的介面稱為函式式介面。沒有必要使用@FunctionalInterface註解標記函式式介面,編譯器不會丟擲任何錯誤。但建議使用@FunctionalInterface註解,以避免意外新增額外的抽象方法。如果一個使用@FunctionalInterface註解標記的介面有超過一個抽象方法,那麼會丟擲一個編譯期錯誤。

語法

@FunctionalInterface
interface interface_name {
   // only one abstarct method declaration
}

示例

@FunctionalInterface
interface Shape {
   void printArea(int x);
}
public class SquareTest {
   public static void main (String args[]) {
      Shape square = (x) -> {     // Lambda Expression
         System.out.println("The area of a square is: "+ x*x);
      };
      square.printArea(7);
   }
}

輸出

The area of a square is: 49

更新時間: 2020-07-10

2 千次觀看

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.