如何在 Java 中的方法引用中使用 this 和 super 关键字?

java 8object oriented programmingprogramming更新于 2025/4/24 5:37:17

方法引用类似于 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

相关文章