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?
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".
You can do something like this
public class WrappedTest {
private Test test;
public Test getTest() { return test; }
public void setTest(Test test) { this.test = test; }
public void delete() { test = null; }
}
"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
test = null;
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:
Integer a = new Integer(1);
Integer b = a;
a = new Integer(2); //does NOT modify variable b
System.out.println(b); //prints 1
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.
int main{
//Create a new test object
Test test = new Test();
// use the object through test
test=null;
}