Saturday, December 27, 2014

Difference between final, finally and finalize

What is the difference between final, finally and finalize? is the most repeating question by the all interviewers. These three words are seems to be similar, that is the reason most of the interviewer shooting this question. As we had good idea about java concepts and we had a discussion about Garbage Collection mechanism also. So understanding the differences of these three words is not a big deal.

final

  1. final is a access modifier
  2. final is applicable for classes, methods and variables
  3. If a variable is declared as final, that variable becomes a constant. We can't perform re-assignment for that variable
  4. If a method is declared as final, we can't override that method in sub class
  5. If a class is declared as final, we can't extends that class any other classes. Which means, we can't create a sub class for that

finally

  1. finally is a block
  2. finally block always associated with try-catch block to perform clean up
  3. The purpose of the finally block is to de-allocate the resources. Suppose DataBase connection is created inside the try block. So DataBase connection should be closed once its usage is over. But there may an exception try block before closing the DataBase connection. But finally block guarantee that, irrespective of whether try block is executed completely or not, finally block will execute

finalize

  1. finalize is a method which is in Object class
  2. finalize method will be called by Garbage Collector just before destroy an object
  3. We know already that, when an object is ready for Garbage Collection. When there is no reference to an object, then that object is ready for Garbage Collection. But de-referenced object may hold some resources which needs to be de-allocated. So we can override the finalize method is our class, there we can write clean up code for an object

No comments:

Post a Comment