finalize() Method in Java and How to Override it?
The Java finalize() method of Object class is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection to perform 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. Remember, it is not a reserved keyword. Once the finalize() method completes immediately, Garbage Collector destroys that object.
Finalization: Just before destroying any object, the garbage collector always calls finalize() method to perform clean-up activities on that object. This process is known as Finalization in Java.
Note: The Garbage collector calls the finalize() method only once on any object.
Syntax:
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, Garbage Collector can call the finalize() method on any java object.
Why finalize() method is used?
finalize() method releases system resources before the garbage collector runs for a specific object. JVM allows finalize() to be invoked only once per object.
How to override finalize() method?
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.
Java
import java.lang.*;
public class demo {
protected void finalize() throws Throwable
{
try {
System.out.println( "inside demo's finalize()" );
}
catch (Throwable e) {
throw e;
}
finally {
System.out.println( "Calling finalize method"
+ " of the Object class" );
super .finalize();
}
}
public static void main(String[] args) throws Throwable
{
demo d = new demo();
d.finalize();
}
}
|
Output:
inside demo's finalize()
Calling finalize method of the Object class
Last Updated :
21 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...