Java新特性-函数式接口

定义

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。

语法:

@FunctionalInterface
public interface MyFunctionalInterface {
//抽象方法
    void abstractMethod();  
//默认方法
default void defaultMethod() { 
        //implement code
    }
//静态方法
    static void staticMethod() { 
        //implement code
    }
 //Object 中覆盖的方法,也就是 equals,toString,hashcode等方法。
    @Override
    boolean equals(Object obj); // java.lang.Object's public method
}

说明:

  1. 函数式接口里允许定义默认方法。 函数式接口里是可以包含默认方法,因为默认方法不是抽象方法,其有一个默认实现,所以是符合函数式接口的定义的;
  2. 函数式接口里允许定义静态方法。 函数式接口里是可以包含静态方法,因为静态方法不能是抽象方法,是一个已经实现了的方法,所以是符合函数式接口的定义的;
  3. 函数式接口里允许定义 java.lang.Object 里的 public 方法。函数式接口里是可以包含Object里的public方法,这些方法对于函数式接口来说,不被当成是抽象方法(虽然它们是抽象方法);因为任何一个函数式接口的实现,默认都继承了 Object 类,包含了来自 java.lang.Object 里对这些抽象方法的实现;

举个例子

//定义函数式接口
@FunctionalInterface
public interface MyFunction<T,F,R> {
    R myFunction(T t,F f);
}

//实现接口
public class MyFunctionDemo {
    public static void main(String[] args) {
        MyFunction<Integer,Integer,Integer> add=(a,b)-> (a+b);
        MyFunction<Integer,Integer,Integer> minus=(a,b)-> (a-b);
        MyFunction<Integer,Integer,Integer> multiply=(a,b)-> (a/b);
        MyFunction<Integer,Integer,Integer> divide=(a,b)-> (a*b);
        System.out.println(calculate(add,1,4));
        System.out.println(calculate(minus,6,4));
        System.out.println(calculate(multiply,1,4));
        System.out.println(calculate(divide,1,4));

    }
    public static Integer calculate(MyFunction<Integer,Integer,Integer> operation,Integer numberA,Integer numberB) {
        return operation.myFunction(numberA,numberB);
    }
}

//结果
5
2
0
4

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容