Advertisement



< Prev
Next >



Java finalize() method





A method named finalize() is executed before an object is de-allocated from the heap memory by the garbage collector. Each class inherits the finalize() method from the Object class, which is a superclass of all java classes. We can override the finalize() method to give it our own preferred definition.




Signature of finalize() method


public void finalize() 





Note :


Method finalize() runs only once in the lifetime of an object, i.e. just before an object is about to be de-allocated from heap memory by the garbage collector.



Advertisement




Example of finalize() method


class A
{

//overriding finalize() method inherited from Object class.
public void finalize() 
{
System.out.println("Object is garbage collected");
}



public static void main(String... ar)
{
Runtime run = Runtime.getRuntime();
A ob;

//Creating 10 objects of class A
for(int i=0; i<10;i++)
{
ob= new A(); 
}

run.gc(); //Making a request to garbage collector to de-allocate unreferenced objects.
}
}


Output -


Object is garbage collected
Object is garbage collected


Program Analysis





Note :




Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON


Advertisement