函數式接口
概念:函數式接口在Java中是指:有且僅有一個抽象方法的接口。
格式:
修飾符 interface 接口名{
一個抽象方法
}
e:
public interface DemoSum {
public abstract int sum(int a, int b);
}
public class DemoTest {
public static void inta(int a, int b ,DemoSum sum){
int s=sum.sum(a, b);
System.out.println(s);
}
public static void main(String[] args) {
//常用的方法
inta(10, 20, new DemoSum() {
@Override
public int sum(int a, int b) {
return a+b;
}
});
//簡化
inta(20,50,(a,b)->a+b);
}
}
簡化後只有一行是不是簡單多了。
如何簡化:
- 一個函數試接口
- 在一個類中把接口作爲參數傳遞
e:
@FunctionalInterface
public interface DemoSsy {
public abstract void dog();
}
public class DomeDoger {
public void eat(DemoSsy dog){
System.out.println("我在吃骨頭");
}
}
然後我們在main方法中調用這個方法
當參數試一個函數式接口我們可以用箭頭來表示
public static void main(String[] args) {
new DomeDoger().eat(()->{
System.out.println("我在吃骨頭");
}
);
}
eat後面的括號代表參數的個數因爲我們沒有參數可以不寫
當我們在函數體內只有一條語句時括號和分號可以省略
public static void main(String[] args) {
new DomeDoger().eat(()->System.out.println("我在吃骨頭"));
}
注意:省略時必須同時省略
@FunctionalInterface註解
與 @Override 註解的作用類似,Java 8中專門爲函數式接口引入了一個新的註解: @FunctionalInterface 。該注 解可用於一個接口的定義上:
@FunctionalInterface
public interface DemoSsy {
public abstract void dog();
}
一旦使用該註解來定義接口,編譯器將會強制檢查該接口是否確實有且僅有一個抽象方法,否則將會報錯。需要注 意的是,即使不使用該註解,只要滿足函數式接口的定義,這仍然是一個函數式接口,使用起來都一樣。