Java Object - finalize() Method
The java.util.Object.finalize() method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
Syntax
protected void finalize() throws Throwable
Parameters
No parameter is required.
Return Value
void type.
Exception
Throwable - the Exception raised by this method.
Example:
In the example below, the java.util.Object.finalize() method is used to override the finalize method to define specified clean-up activities.
import java.lang.*; import java.util.*; public class MyClass { protected void finalize() throws Throwable { try { System.out.println("Inside MyClass finalize"); } catch (Throwable e) { throw e; } finally { System.out.println("Calling finalize of the Object class"); //Calling finalize of Object class super.finalize(); } } public static void main(String[] args) throws Throwable { //Creating a MyClass object MyClass x = new MyClass(); //calling finalize of MyClass x.finalize(); } }
The output of the above code will be:
Inside MyClass finalize Calling finalize of the Object class
❮ Java.lang - Object