Is it possible to set to null an instance of a class within the class. For example, could I do something like this
int main{
//Create a new test object
Test test = new Test();
//Delete that object. This method should set the object "test" to null,
//thus allowing it to be called by the garbage collector.
test.delete();
}
public class Test{
public delete(){
this = null;
}
}
I have tried this and it does not work. Using "this = null" I get the error that the left hand side needs to be a variable. Is there a way to achieve something similar?
You can do something like this
"
this
" is a final variable. you can not assign any values to it.If you want to set the reference null you can do this
this
is a reference to the instance of your class. When you modify a reference variable, it only modifies that reference and nothing else. For example:An instance of an object doesn't know which references might be referring to it, so there's no way that code within the object can null those references. What you're asking for isn't possible(*).
* at least not without adding a pile of scaffolding to keep track of all the references, and somehow inform their owners that they should be nulled - in no way would it be "Just for convenience".
Is it possible to set to null an instance of a class within the class?.
You cannot do this from the member methods of the same instance. So,
this=null
or that sort of thing will not work.How come one set an instance to an null?
That question itself is wrong, we set references to
null
but not instances. Unused objects automatically garbage collected in java.If you set
test=null
it will eventually gets garbage collected.