Open In App

finalize() Method in Java and How to Override it?

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java code to show the
// overriding of finalize() method
 
import java.lang.*;
 
// Defining a class demo since every java class
// is a subclass of predefined Object class
// Therefore demo is a subclass of Object class
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");
 
            // Calling finalize() of Object class
            super.finalize();
        }
    }
 
    // Driver code
    public static void main(String[] args) throws Throwable
    {
 
        // Creating demo's object
        demo d = new demo();
 
        // Calling finalize of demo
        d.finalize();
    }
}


Output:

inside demo's finalize()
Calling finalize method of the Object class


Last Updated : 21 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads