在Java中,我将如何执行以下操作:
Foo bar = new Foo();
Foo a = bar;
Foo b = bar;
bar = null;//will only set bar to null. want to set value of bar to null rather than the reference to null.
Run Code Online (Sandbox Code Playgroud)
是否可以设置变量bar,a并且b(都是引用bar)仅在访问bar时为null?如果是这样,有人可以解释如何这样做.
这在Java中是不可能的.你不能设置引用a和bnull使用bar.
原因 - Java pass by value不是pass by reference.
不,在Java中是不可能的.
我稍微解释一下你的代码中发生了什么.在这里,Foo bar = new Foo();您创建了对象Foo并引用了该变量bar.
在这里Foo a = bar;,Foo b = bar;你把引用放在变量a和b.所以你现在有一个对象和三个指向他的变量.
在这里bar = null;你清除bar变量.所以你有两个变量(a和b)指向对象,一个变量(bar)没有引用.