finalize method is a method of Object class. It is invoked by GC just before the destruction of an object. It is used to free all the system resources held by the object .
It must be overridden by a class in order to perform deallocation of resources of related objects. It is preceded with protected access specifier and doesn’t perform any special action. If there is an exception occurred it would be handled by throwable.
Syntax:
protected void finalize() throws Throwable { }
Before destroying an object GC invokes finalize method with the purpose of resource deallocation and perform cleaning operation.
It allows us to perform some action before destroying a particular object. There may be a situation where an object is holding some resources and it is needed to be freed before the object gets destroyed.
So, a process of releasing resources held by the unreachable object and invoked just before the object’s destruction is called finalization. This method invokes beforehand reclaiming an object.
protected void finalize() { // action }
class Sample { @Override protected void finalize () { System.out.println ("I am in Finalize Method"); } } public class FinalizeExample { public static void main (String[]args) { Sample obj = new Sample (); obj = null; System.gc (); } }
Output:
I am in Finalize Method
This post was last modified on December 27, 2020