Is it possible to set null for an instance of a class inside a class

Is it possible to set a null instance of a class inside a class. For example, can 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 tried this and it does not work. Using "this = null", I get the error that the left side should be variable. Is there a way to achieve something like this?

+4
source share
5 answers

An instance of an object does not know which links can reference it, so there is no way that the code inside the object can nullify these links. What you ask for is impossible (*).

* at least not adding a bunch of scaffolding to keep track of all the links, and somehow inform their owners that they should be reset - in no way would be “just for convenience”.

+6
source

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; } } 
+4
source

" this " is the final variable. you cannot assign any values ​​to it.

If you want to set the reference number to zero, you can do this

 test = null; 
0
source

this is a reference to an instance of your class. When you change a reference variable, it only modifies that link and nothing else. For instance:

 Integer a = new Integer(1); Integer b = a; a = new Integer(2); //does NOT modify variable b System.out.println(b); //prints 1 
0
source

Is it possible to set to null an instance of a class within the class?.

You cannot do this from member methods of the same instance. So this=null or something will fail.

How is it that the instance is set to null?

This question is wrong, we are setting references to null , but not to instances. Unused objects are automatically garbage collected in java.

If you set test=null , it will eventually receive garbage collection.

  int main{ //Create a new test object Test test = new Test(); // use the object through test test=null; } 
0
source

Source: https://habr.com/ru/post/1484469/


All Articles