1. 程式人生 > 其它 >OO-第三單元總結

OO-第三單元總結

1.  什麼是函式式介面

  • 只包含一個抽象方法的介面,稱為函式式介面
  • 我們可以在任意函式式介面上使用@FunctionInterface註解,這樣做可以檢查它是否是一個函式式介面,同時javadoc也會包含一條宣告,說明這個介面是一個函式式介面

2.  函式式介面的使用

2.1.  自定義函式式介面

package com.chenly.fun;

/**
 * @author: chenly
 * @date: 2022-11-29 16:55
 * @description:
 * 函式式介面:有且只有一個抽象方法的介面,稱之為函式式介面
 *    當然介面中可以包含其他的方法(預設,靜態,私有)
 *
 *    @FunctionalInterface
 *    作用:可以檢測介面是否是一個函式式介面
 
*/ @FunctionalInterface public interface MyFunctionalInterface { //定義一個抽象方法 public abstract Object method(); }

2.2.  實現類MyFunctionalInterfaceImpl

package com.chenly.fun;

/**
 * @author: chenly
 * @date: 2022-11-29 16:56
 * @description:
 * @version: 1.0
 */
public class MyFunctionalInterfaceImpl implements
MyFunctionalInterface { @Override public Object method() { System.out.println("實現類重寫介面中的抽象方法"); return null; } }

2.3.  函式式介面的使用

package com.chenly.fun;

/**
 * @author: chenly
 * @date: 2022-11-29 16:57
 * @description:  函式式介面的使用:一般可以作為方法的引數和返回值型別
 * @version: 1.0
 */
public
class Demo { /**定義一個方法,引數使用函式式介面MyFunctionalInterface*/ public static Object show(MyFunctionalInterface myInter){ return myInter.method(); } public static void main(String[] args) { //呼叫show方法,方法的引數是一個介面,所以可以傳遞介面的實現類物件 show(new MyFunctionalInterfaceImpl()); //呼叫show方法, 匿名內部類的方式 show(new MyFunctionalInterface() { @Override public Object method() { System.out.println("使用匿名內部類重寫介面中的抽象方法"); return null; } }); //呼叫show方法,使用Lambda表示式 show(()->{ System.out.println("使用Lambda重寫介面中的抽象方法"); return null; }); //簡化Lambda表示式 //show(()-> System.out.println("使用Lambda重寫介面中的抽象方法")); } }