Reputation: 1766
In Java, how would I do the following:
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.
Is it possible to set the variables bar
, a
and b
(all are a reference to bar
) to null only with access to bar? If so, could somebody please explain how to do so.
Upvotes: 8
Views: 5676
Reputation: 1148
No, it is not possible in Java.
I a little explain what happened in your code.
Here Foo bar = new Foo();
you created object of Foo
and put reference to the variable bar
.
Here Foo a = bar;
and Foo b = bar;
you put the reference to the variables a
and b
. So you have now one object and three variables pointing to him.
Here bar = null;
you clear the bar
variable. So you have two variables (a
and b
) pointing to the object and one variable (bar
) without reference.
Upvotes: 7
Reputation: 417
There isn't really a destructor in Java like there is in C:
If you knew that you wanted to set multiple objects to null, then you would probably use an array of Foo rather than declaring them as separate objects. Then use loops for consturctor calls, instatiation /initialization.
Foo bar = new Foo();
Foo array[2]
for (int i=0; i<array.length; i++) {
array[i] = bar;
}
Then you could use a loop at the end
for (int i=0; i<array.length; i++) {
array[i] = null;
}
This is the strategy you would want for Data Structures because you can handle any number of objects, for recursion etc.
Upvotes: 2
Reputation: 2277
That's not possible in Java.You can not set reference a
and b
null using bar
.
Reason - Java is pass by value
not pass by reference
.
Upvotes: 5