Function interface 接口就是一个有且只有一个抽象方法
但是可以有非抽象方法 的接口
1.可以用lambda表达式
2.也可以用方法的引用
其实在jdk8之前已经有部分的函数式接口
如:
Java.lang.Runnable
Java.util.Comparator
Java.IO.FileFilter
在jdk8以后,新添加的一个函数式接口
Java.util.Function,其中包含了很多的类
如:
Consumer
Predicate
Supplier
等…
例:
@FunctionalInterface
public interface GreetingService {
public void sayMessage(String message);
}
测试:
public class Demo1 {
public static void main(String[] args) {
GreetingService service1 = (message)->System.out.println("hello"+message);
service1.sayMessage("zhangsan");
GreetingService service2 =System.out::print;
service2.sayMessage("lisi");
}
}
默认方法:
-
在接口中可以放置有方法体的方法,但方法体前用default来修饰
-
在接口中添加默认方法是用来给所有的子类提供同一个功能
-
在接口中可以放置静态方法,可以给方法体
例:
public class Demo1 {
public static void main(String[] args) {
Vehicle v = new Car();
v.print();
}
}
interface Vehicle{
default void print(){
System.out.println("这是一辆车");
}
static void laba(){
System.out.println("laba想了");
}
}
interface FourWheeler{
default void print(){
System.out.println("是是一辆四轮车");
}
}
class Car implements Vehicle,FourWheeler{
@Override
public void print() {
Vehicle.super.print();
FourWheeler.super.print();
Vehicle.laba();
System.out.println("我是一辆四轮小轿车");
}
}