![]() |
VOOZH | about |
The finalize() method in Java is called by the Garbage Collector just before an object is destroyed. It allows the object to perform a clean-up activity. Clean-up activity means closing the resources associated with that object, like Database Connection, Network Connection or we can say resource de-allocation.
Just before destroying any object, the garbage collector always calls the finalize() method to perform clean-up activities on that object. This process is known as Finalization in Java. The Garbage collector calls the finalize() method only once on any object.
Note: The finalize() method has been deprecated since Java 9 and removed in Java 18 (JEP 421).
It is not recommended for use in modern Java applications. Prefer alternatives like try-with-resources, AutoCloseable or java.lang.ref.Cleaner for resource management and cleanup.
protected void finalize() throws Throwable
Since the Object class contains the finalize method, hence finalize method is available for every Java class since Object is the superclass of all Java classes. Since it is available for every Java class, the Garbage Collector can call the finalize() method on any Java object.
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. In order to override this method, we have to define and call finalize within our code explicitly.
Example: Overriding finalize() Method
Inside Geeks's finalize() Calling finalize() of Object class