Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, how can we destruct an instance of a class from a method within the class

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?
    }
  }
}
like image 641
Saurabh Agarwal Avatar asked Jun 11 '12 12:06

Saurabh Agarwal


People also ask

How do you destroy an instance in Java?

The Java Object class provides the finalize() method that works the same as the destructor. The syntax of the finalize() method is as follows: Syntax: protected void finalize throws Throwable()

How is Java object destruction done?

A destructor is a special method that gets called automatically as soon as the life-cycle of an object is finished. A destructor is called to de-allocate and free memory. The following tasks get executed when a destructor is called. Destructors in Java also known as finalizers are non-deterministic.

How are objects destroyed in Java Explain How do you release any resource before object destruction?

Every time we create an object, Java automatically allocates the memory on the heap. Similarly, whenever an object is no longer needed, the memory will automatically be deallocated. In languages like C, when we finish using an object in memory, we have to deallocate it manually.


1 Answers

You don't "destruct" objects in Java. This is wrong-headed. Don't do it.

Objects are created on the heap in Java. They live as long as there's a reference that points to them. The garbage collector cleans up the mess.

You should certainly do what you can to make sure that you don't accumulate and hold onto references unnecessarily (e.g. Listeners in Swing).

But your proposal is not the right thing at all. Cease and desist.

like image 72
duffymo Avatar answered Oct 06 '22 02:10

duffymo