一、开门见山
使用lambda表达式,新建一个类的时候,必须满足以下三点:
- 新建的类必须是接口,此接口称为函数式接口
- 此接口只能有一个非抽象类接口,但是可以使用default参数添加扩展方法
- 忽略object类方法
二、测试
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
,这样会在接口加入多余的方法的时候就报错。
网友评论