the finalize() method is called by the garbage collector before an object is reclaimed. It’s defined in the Object class and can be overriden to perform cleanup
protected void finalize() throws Throwable
rarely used in modern java as try catch is more preferrable
deprecated in java 9 due to performance issues and unreliability.
class Resource {
@Override
protected void finalize() throws Throwable {
System.out.println("Cleaning up resource");
// Perform cleanup
super.finalize();
}
}
class Main {
public static void main(String[] args) {
Resource r = new Resource();
r = null; // Eligible for GC
System.gc(); // Suggests GC, may trigger finalize()
}
}