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
- final is a access modifier
- final is applicable for classes, methods and variables
- If a variable is declared as final, that variable becomes a constant. We can't perform re-assignment for that variable
- If a method is declared as final, we can't override that method in sub class
- 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
- finally is a block
- finally block always associated with try-catch block to perform clean up
- 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
- finalize is a method which is in Object class
- finalize method will be called by Garbage Collector just before destroy an object
- 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