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 the 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 :


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



Advertisement




Example of finalize() method


//Java - 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(); 
	}

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


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

C#, PYTHON and DJANGO


Advertisement