Nulling variable does not invalidate method reference [duplicate]

这一生的挚爱 提交于 2019-12-10 16:07:08

问题


Why does the code not throw a NullPointerException when I use a method reference tied to a variable dog which I later assigned null to?

I am using 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));
    }
}

回答1:


The dog::eat method reference captures the instance referenced by dog, so when you call function.apply(2), the eat method is executed for that instance. It doesn't matter that the dog variable no longer references that instance.




回答2:


The variable dog used at the lambda expression is visible only at the scope of the lambda expression since its definition and nullifying the dog will not affect the method reference dog::eat.

An example without usage of dog with the same functionality:

Function<Integer, Integer> function = new Dog()::eat;


来源:https://stackoverflow.com/questions/56457483/nulling-variable-does-not-invalidate-method-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!