What is the difference between final, finally and finalize?

The similarity in the names may be one of the reason to ask this question in many number of interviews.

final:  

final is a modifier applicable for classes, methods and variable.
  • If we declare a variable as a final, it will become constant and we cannot perform reassignment to that variable. 
  • If a method is declared final in a class, the method cannot be overridden in the child classes.
  • If a class is declared as final, then the class cannot be extended ie., we cannot create a child class to that class.

finally:

finally is a block always associated with try / catch block to maintain cleanup code.
try
{
   // Risky code
}
catch(Exception e)
{
    //handling part of code
}
finally
{
    //cleanup code(like resource de-allocation)
}

 finalize:

finalize() is a method present in "object" class. finalize is called by garbage collector to perform cleanup activities before destroying an object.

Note:

finally block is meant for cleanup activities related to the try block. The resources which are opened in the try block code are closed in the finally block. Whereas, finalize() method is related to cleanup the resources which are related to the unused objects and is related to garbage collector.

No comments:

Post a Comment