Wednesday, 22 August 2018

final, finally and finalize in Java

final :
  • final is a modifier applicable for classes, methods and variables.If a class is declared as final then we can't extend that class means we can not create child class for that class.
  • If a method is declared as final then we can't override that method in the child class.
  • If a variable is declared as final then it will become constant and we can't perform re-assignment for that variable.
finally : 
  • finally is a block always associated with try catch to maintain clean up code.
  • Code in the finally code will always be executed even if an exception is thrown.
  • finally block can be used instead of catch block.
  • Sample Code : 
       try
       {
            //risky code
       }
       catch(X e)
       {
            //Handling code
       }
       finally
      {
            //clean up code 
      }

finalize : 
  • finalize() is a method which is present in the object class.
  • Garbage Collector calls the finalize() method just before destroying the object to check which objects are eligible to garbage collect.
  • It is used to clean or release the resources i.e.closing database connection.
Important Point to remember :
      finally is meant for clean up activities related to try catch block and finalize() is meant for clean up activities related to object.

No comments:

Post a Comment