Java8新特性之 函數式接口FunctionalInterface詳解

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();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

函數式接口的特徵:

  1. 接口中只定義了一個抽象方法。如 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();

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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();

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

函數式接口的主要作用

使用@FunctionalInterface可以防止以後在接口中添加新的抽象方法簽名。就是限定了只能用此抽象方法,別的方法不能用。直接限制死。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章