Java 8已经公布有一段时间了,种种迹象表明Java 8是一个有重大改变的发行版。本文将java8的一个新特性 函数式接口 单独深度剖析。
函数式接口的范例:
@FunctionalInterface是JDK 8 中新增的注解类型,用来描述一个接口是函数式接口。例如我们熟悉的Runnable 接口:
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
函数式接口的特征:
- 接口中只定义了一个抽象方法。如 FunctionInteTest接口中,只有一个sayHello()方法。
package in;
/**************************************
* *** http://weibo.com/lixiaodaoaaa **
* *** create at 2017/6/8 22:06 ******
* ******* by:lixiaodaoaaa ***********
**************************************/
@FunctionalInterface
public interface FunctionInteTest {
public abstract void sayHello();
}
2.接口中允许存在重写Object类的抽象方法。如在FunctionInteTest接口中,新增一个toString()方法,仍然不会报错。因为FunctionInteTest接口的实现类一定是Object类的子类,继承了toString()方法,也就自然实现了TestInterface 接口定义的抽象方法toString()。
/**************************************
* *** http://weibo.com/lixiaodaoaaa **
* *** create at 2017/6/8 22:06 ******
* ******* by:lixiaodaoaaa ***********
**************************************/
@FunctionalInterface
public interface FunctionInteTest {
public abstract void sayHello();
public abstract String toString();
}
函数式接口的主要作用
使用@FunctionalInterface可以防止以后在接口中添加新的抽象方法签名。就是限定了只能用此抽象方法,别的方法不能用。直接限制死。