gpt4 book ai didi

java - 空变量不会使方法引用无效

转载 作者:搜寻专家 更新时间:2023-11-01 01:48:49 28 4
gpt4 key购买 nike

<分区>

当我使用绑定(bind)到变量 dog 的方法引用时,为什么代码不抛出 NullPointerException,我后来将 null 赋值给它?

我正在使用 Java 8。

import java.util.function.Function;

class Dog {
private int food = 10;

public int eat(int num) {
System.out.println("eat " + num);
this.food -= num;
return this.food;
}
}

public class MethodRefrenceDemo {

public static void main(String[] args) {
Dog dog = new Dog();
Function<Integer, Integer> function = dog::eat;

dog = null;

// I can still use the method reference
System.out.println("still have " + function.apply(2));
}
}

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com