Java 中函式式介面的規則有哪些?
一個函式 介面 是一類特殊的介面,其中正好包含一個抽象方法,其中 lambda 表示式引數和返回型別相匹配。它為 lambda 表示式和方法引用提供了目標型別。
函式介面的規則
- 函式介面必須恰好包含一個抽象方法。
- 函式介面包含任意數量的預設方法,因為它們不是抽象的且已經由函式介面本身提供了實現。
- 函式介面宣告一個抽象方法來覆蓋java.lang.Object 中的一個公共方法,這仍然被認為是函式介面。其原因是任何實現此介面的實現類都可以為該抽象方法提供實現,具體可透過超類 或由實現類本身來定義。
語法
@FunctionalInterface
interface <interface-name> {
// only one abstract method
// static or default methods
}示例
import java.util.Date;
@FunctionalInterface
interface DateFunction {
int process();
static Date now() {
return new Date();
}
default String formatDate(Date date) {
return date.toString();
}
default int sum(int a, int b) {
return a + b;
}
}
public class LambdaFunctionalInterfaceTest {
public static void main(String[] args) {
DateFunction dateFunc = () -> 77; // lambda expression
System.out.println(dateFunc.process());
}
}輸出
77
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP