Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set an Object to be null from within itself?

Tags:

java

I know that this = null is illegal.

I'm wondering if there's some other way to have an object clean itself up.

my desire is to be able to do something like this:

A a = new A();

a.doStuffAndDisappear();

if(a == null){
     //this is true after my doStuffAndDisappear() method.
}

I suspect there's no way to make this happen, but thought it would be worth asking.

like image 960
Yevgeny Simkin Avatar asked Aug 17 '13 21:08

Yevgeny Simkin


People also ask

Can you set object to null?

An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.

Can you set an object to null in Java?

Firstly, you never set an object to null. That concept has no meaning. You can assign a value of null to a variable, but you need to distinguish between the concepts of "variable" and "object" very carefully.

Can a static object be null?

That is totally expected, static initialization happens on different events which none of them occurs before your assign, so the static attribute will be null anyway.

How do I assign a null to an object in C#?

In C#, you can assign the null value to any reference variable. The null value simply means that the variable does not refer to an object in memory. You can use it like this: Circle c = new Circle(42); Circle copy = null; // Initialized ... if (copy == null) { copy = c; // copy and c refer to the same object ... }


1 Answers

No, because a is a reference (not an object as in this question's title) and no method can modify the value of a reference except the method in which it is defined (I assume from the code context that a is a local variable).

Since Java doesn't have pass-by-reference, what you ask cannot be done: there's no way to collect addresses-of references in order to manage the addresses pointed to. You might use a wrapper object, but not sure what'd be the point.

like image 176
Raffaele Avatar answered Sep 23 '22 20:09

Raffaele