what is finalize method in java

what is finalize method in java

1 year ago 78
Nature

The finalize() method in Java is a method of the Object class that is used to perform cleanup activity before destroying any object. It is called by the garbage collector before destroying the objects from memory. The finalize() method is a non-static and protected method of the java.lang.Object class, which is the superclass of all Java classes. Being an object class method, the finalize() method is available for every class in Java, and hence, the garbage collector can call it on any Java object for clean-up activity.

The finalize() method releases all the resources used by the object before it is deleted/destroyed by the garbage collector. Once the clean-up activity is done by the finalize() method, the garbage collector immediately destroys the Java object. The JVM permits invoking the finalize() method only once per object.

To override the finalize() method, we have to define and call finalize() within our code explicitly. The finalize() method, which is present in the Object class, has an empty implementation. In our class, clean-up activities are there. Then we have to override this method to define our clean-up activities.

It is important to note that the finalize() method has severe performance penalties and has been deprecated since Java 9. It should be used carefully when needed.

Read Entire Article