Why Java Does Not Support Destructor?

In any programming language, whenever we declare and create an object it takes some bytes of memory in the heap memory. After the usage of the objects, we need to delete them from heap memory as they might be responsible for taking some unwanted space. Let’s assume we forget to remove them and you are not able to write your program completely. This will suggest that our heap memory is exhausted completely.

So destructors are used to free memory by destroying unwanted objects.

Does Java Support Destructor?

In Java, we don’t have specific destructors. Java already contains a garbage collector which runs automatically on JVM. Whenever we run a program garbage collector will always check the unwanted objects and deallocates the memory used by them.

What Problem Does Garbage Collector Cause?

The garbage collector is handled by JVM whereas the destructor is handled by the programmer itself. This is the one and only important difference between them. The destructor shares just after deallocating the memory of the object whereas the garbage collector shares after the completion of the program. So whenever the programmer needs immediate access to the memory management then the garbage collector fails.

How to Solve this Problem?

In java, it is hard to run the garbage collector forcefully and manually. Still, java has an alternative method named finalize() which functions the same as destructors.

Syntax of the finalize method is written below:

The finalize method comes from the object class and it provides an extra layer of security. Basically, it removes the connection between the resources and the object before we delete the object. Therefore it can be used only once for each object, if you try to do it otherwise then the JVM ignores the request.

It is not suggested to depend on the finalize method in java, as there is no guarantee that the finalize method will be called automatically. But you can override it according to your needs.

Here is an example through which we can see how to override the finalize method.

Output:

Leave a Comment

Your email address will not be published. Required fields are marked *