In java, how can we destruct an instance of a class from a method within the class
destructor, garbage-collection, java
Solution
this=null; //Is this statement valid? Why / Why not?
It is not valid Java because `this` is not an lvalue; i.e. not something you can assign to. This is a compilation error, just like `42 = i;` is a compilation error.
(The JLS says the following about assignments: "The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs." - JLS 15.26.1 The JLS text then goes on to list the different things that qualify as variables, and `this` is not one of them.)
Besides, as duffymo says, it is a totally wrong-headed thing to do in Java. Just let the GC do its job.
Problem
I approached it similar to the case of deleting any usual object, ie, simply making the reference null and letting the Garbage Collector do its job. However for equating to null within a class, the only reference to the object is "this". So is the code for the following class valid: ``` class A{ public A(){ //Init } public void method destruct(){ if(someCondition){ this=null; //Is this statement valid? Why / Why not? } } } ```