如何在Java的方法引用中使用this和super关键字?
方法引用类似于在不执行该方法的情况下引用方法的lambda表达式,并且“::”运算符可用于将方法名称与方法引用中对象或类的名称分开。
这些方法可以在Java中借助this和super关键字进行引用。super关键字可以用作限定符来调用类或接口中重写的方法。
语法
this::instanceMethodTypeName.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
热门推荐
4 聚餐会祝福语简短
10 校长退休文案祝福语简短
11 结婚喜庆的祝福语简短
12 祝美术老师祝福语简短
13 青春告白祖国简短祝福语
14 离别简短的祝福语大全
15 钱包祝福语简短10字
16 蛋糕祝老师祝福语简短
17 春天变冷祝福语简短
18 订婚新发言简短祝福语