概念引入:函数式接口
定义:
- 接口声明了@FunctionalInterface注解。
- 某接口只有一个抽象方法,即使没有@FunctionalInterface注解,编译器依然将该接口看作函数式接口。
- 函数式接口加上@FunctionalInterface注解的好处是编译器会检查该接口是否符合规则,预防不必要的错误(编译器:谁让你们愚蠢的人类老是写错别字)
- 函数式接口重写父类的方法,比如Object的toString方法,不会计数进抽象方法的个数中
例子:
//1.基本写法
@FunctionalInterface
interface InterfaceTest {
void buling();
}
//2.下面这种写法就会编译不通过
@FunctionalInterface
interface InterfaceTest {
void buling();
void test();
}
//3.编译通过,toString方法并不计入数目
@FunctionalInterface
interface InterfaceTest {
@Override
String toString();
void buling();
}
/*
* @param <T> the type of the input to the operation
//T是输入的操作类型,比如丢进来一个println方法,类型就是函数。
* @since 1.8
*/
@FunctionalInterface
public interface Consumer<T> { //表示只进行消费,比如只进行打印,不需要返回值的情况。
/**
* Performs this operation on the given argument.
* @param t the input argument
*/
void accept(T t);
}
函数式接口的实例的创建方式:
that instances of functional interfaces can be created with
lambda expressions, method references, or constructor references.
ps.全部详情请参见 FunctionalInterface.java上的注释
函数式接口的实例创建方式有三种,分别是lambda表达式、方法引用和构造函数引用
为何函数式接口只能有一个抽象方法?
@FunctionalInterface
interface TestInterface {
void OnlyMethod();//c.因为这个方法并不需要参数 ===> 跳转到d.
// a.假设这里可以存在有一个AnotherMethod ===> 跳转到b.
}
class Test {
void speak(TestInterface testInterface){
System.out.println("Cat");
testInterface.OnlyMethod();
System.out.println("Dog");
}
public static void main(String[] args) {
Test test = new Test();
//b. 那么此处 ()->{}的写法就不能成立,因为并不知道要调用哪个方法,所以只有接口内方法唯一,才可以直接调用
//d. 所以 ()->{}的小括号内就不需要传递参数
test.speak(()->{
System.out.println("------------");
});
}
}
网友评论