我們如何在 Java 中的方法引用中使用 this 和 super 關鍵字?


方法引用類似於一個lambda 表示式,它引用方法而不會執行它,並且 "::" 運算子可以用來分隔方法引用中方法名與物件或類名。

可以在 Java 中藉助 this 和 super 關鍵字 來引用方法。super 關鍵字可以用作限定符,以在類或介面中呼叫重寫的方法

語法

this::instanceMethod
TypeName.super::instanceMethod

示例

import java.util.function.Function;

interface Defaults {
   default int doMath(int a) {
      return 2 * a;
   }
}
public class Calculator implements Defaults {
   @Override
   public int doMath(int a) {
      return a * a;
   }
   public void test(int value) {
      Function<Integer, Integer> operator1 = this::doMath;
      System.out.println("this::doMath() = " + operator1.apply(value));

      Function<Integer, Integer> operator2 = Defaults.super::doMath;
      System.out.println("Defaults.super::doMath() = " + operator2.apply(value));
   }
   public static void main(String[] args) {
      Calculator calc = new Calculator();
      calc.test(10);
   }
}

輸出

this::doMath() =  100
Defaults.super::doMath() = 20

更新於: 11-Jul-2020

912 次瀏覽

開啟你的 職業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.