Difference between final, finally and finalize

Difference between final, finally and finalize

final:

  • final is the modifier, applicable for classes, method and variables.
  • If a class declare as final then we cannot extends that class. Means we cannot create child class for that class. Means inheritance is not possible for final class.
  • If a method is final then we cannot override that method in the child class.
  • If a variable declare as final then we cannot perform re-assignment for that variable.

finally:

  • finally is a block, always associated with try-catch block to maintain cleanup code.
try cath in java 
The specialty of  final block is it will be executed always respective of whether exception is raised or not raised or whether handled or not.


finalize:

  • finalize() is a method, always invoked by garbage collector just before destroying an object to perform cleanup activities.
  • Once finalize() method completes immediately garbage collectors destroy that object.

Note:

  • finally block is responsible to perform cleanup activity to try block. Means whatever resource we can open at the part of try block will be closed inside finally block. 
  • Where as finalize() method is responsible to perform cleanup activities related to object. Means whatever resource associated with the object will be de-allocated before destroying an object by using finalize() method
 

Various possible combination of try-catch-finally

  •  In try - catch - finally order is important.
  • Whenever we are writing try compulsory  we should write catch or finally. Otherwise we will get  compile time error. Means try without catch or finally is invalid.
  • Whenever we are writing catch block, try block must be required. Means catch without try is invalid.
  • Whenever we are writing  finally block, try block must be required. Means finally block without try is invalid.
  • Inside try- catch- finally and block , we can declare try - catch and finally block. Means nesting of try-catch finally is allowed.
  • For try- catch and finally blocks curly braces ( {} )  are mandatory.
  • If is are using try with finally, and any exception occur then after executing the finally block, the program terminates abnormally.
Possible combination of try-catch and finally 
Possible combination of try-catch and finally 
 
 
Possible combination of try-catch and finally 
 
 
 
RAKESH RAKA

I am Rakesh Raka, senior software engineer (JAVA) in Sopra Steria.

Post a Comment (0)
Previous Post Next Post