What is the purpose of overriding a finalize() method in Java?

JavaObject Oriented ProgrammingProgramming

The finalize() method is a pre-defined method in the Object class and it is protected. The purpose of a finalize() method can be overridden for an object to include the cleanup code or to dispose of the system resources that can be done before the object is garbage collected. If we are overriding the finalize() method then it's our responsibility to call the finalize() method explicitly. The finalize() method can be invoked only once by the JVM or any given object.

Syntax

protected void finalize() throws Throwable

Example

public class FinalizeMethodTest {
   protected void finalize() throws Throwable {
      try {
         System.out.println("Calling finalize() method of FinalizeMethodTest class");
      } catch(Throwable th) {
         throw th;
      } finally {
         System.out.println("Calling finalize() method of Object class");
         super.finalize();
      }
   }
   public static void main(String[] args) throws Throwable {
      FinalizeMethodTest test = new FinalizeMethodTest();
      String str = "finalize() method in Java";
      str = null;
      System.out.println(str);
      test.finalize();
   }
}

Output

null
Calling finalize() method of FinalizeMethodTest class
Calling finalize() method of Object class
raja
Published on 21-Aug-2019 12:17:21
Advertisements