java中,经常看到接口上有@FunctionalInterface注解,例如:java.lang.Runnable接口的定义声明:
@FunctionalInterface注解目的是为了声明一个接口是functional interface。一个functional interface是一个接口,没有声明为sealed,并且只能有一个抽象函数(Object的public函数除外)。注意此处对“一个”的含义,可以通过下面的样例来理解。
package com.thb;
@FunctionalInterface
public interface InterfaceA {
/*
* 接口InterfaceA只有一个抽象函数,并且这个抽象函数不是Object的public函数,所以InterfaceA是Functional Interface
*/
int m1(String str);
}
package com.thb;
@FunctionalInterface
public interface InterfaceB extends InterfaceA {
/*
* 接口InterfaceB继承了接口InterfaceA中的抽象函数,只有一个抽象函数,
* 所以InterfaceB是Functional Interface
*/
}
package com.thb;
@FunctionalInterface
public interface InterfaceC {
/*
* 接口InterfaceC的抽象函数是Object中的public成员函数,此外没有声明其它抽象函数,
* 所以InterfaceC不是Functional Interface
*/
String toString(); // 这个函数是Object的public成员函数
}
package com.thb;
@FunctionalInterface
public interface InterfaceD extends InterfaceA {
/*
* 接口InterfaceD除了继承InterfaceA,此外又定义了一个抽象函数,但InterfaceA中
* 已经有一个抽象函数了,这样等于定义了两个抽象函数,所以InterfaceD不是Functional Interface
*/
int m2(int i);
}
package com.thb;
@FunctionalInterface
public interface InterfaceE {
/*
* 接口InterfaceE定义了一个抽象函数,另外还有Object的一个public函数,
* 等于只有一个抽象函数,所以InterfaceE是Functional Interface
*/
int m1(String str);
String toString(); // Object中的public函数
}
package com.thb;
@FunctionalInterface
public interface InterfaceF {
/*
* 接口InterfaceF定义了一个抽象函数,尽管函数clone与Object的clone名字相同,
* 但在Object中的clone函数不是public,所以InterfaceF是Functional Interface
*/
public Object clone(); // Ojbect中的函数clone是protected
}
package com.thb;
@FunctionalInterface
public interface InterfaceG {
/*
* 接口InterfaceG定义了两个抽象函数,这些抽象函数也不是Object的public函数,
* 所以InterfaceG不是Functional Interface
*/
void m1(String str);
int m2(int i);
}
package com.thb;
@FunctionalInterface
public interface InterfaceH extends InterfaceA, InterfaceE {
/*
* 接口InterfaceH继承的两个接口InterfaceA和InterfaceE中都定义了抽象函数
* m1(String str)并且签名相同,所以实质上等于只有一个抽象函数,所以
* InterfaceH是Functional Interface
*/
}