函数式接口 @FunctionalInterface

2019-09-17  本文已影响0人  steamed_bun

一、开门见山

使用lambda表达式,新建一个类的时候,必须满足以下三点:

二、测试

1、准备一个接口
public interface MyTest {
    void test1();
}
2、使用lambda表达式实现该接口
public static void main(String[] args) {
    MyTest myTest = () -> System.out.println("hello world!");
    myTest.test1();
}

得到输出为:hello world!

3、如果接口类里面有多个方法行不行呢?--- 可以

1⃣️、在接口中加入一个方法

public interface MyTest {
    void test1();
    void test2();
}

2⃣️、会看到报如下错误
Multiple non-overriding abstract methods found in interface--在接口中找到多个非重写抽象方法
找到重点词多个抽象方法,那就是需要将抽象方法减少喽,使用default关键字,改造代码如下:

public interface MyTest {
    void test1();
    default void test2() {
        System.out.println("Bye bye world!");
    }
}

3⃣️、再次调用

public static void main(String[] args) {
    MyTest myTest = () -> System.out.println("hello world!");
    myTest.test1();
    myTest.test2();
}

out:

hello world!
Bye bye world!
4、如何声明一个接口为函数式接口

在接口上使用@FunctionalInterface,这样会在接口加入多余的方法的时候就报错。

上一篇 下一篇

猜你喜欢

热点阅读