Sunday, 6 October 2013

Final,finally and finalize in java.

This is one of the most famous interview question which is being asked. In this post i will try to explain these three keyword .

Following are the some important points about final in java:
  • If you declare final with variable then that will be considered as constant.You have to initialize constant variable when it is declared or in constructor other wise it throws compile time error.
  • If you use final keyword with method then that method will not be overridden(Overloading and Overriding).
  • If you use final keyword with class then that class can not be extended.
Ex. final int a=12;  //final variable declaration.
      final class Test{ //final class declaration.
      }
    
     class Test
   {
     final void fun() //final method declaration.
     {
     }
   }
    
Few important points about finally :


  • We use finally in context of exception handling.
  • finally is the block of code which it executes either exception is thrown or not.
  • In finally we normally do the task like db connection close,releasing the locked resources...etc
  • In one case finally block will not be executed if you exit from the execution.

Few important points about finalize :
  • finalize is the protected method which is used in context of garbage collection.
  • Signature of this method is protected void finalized() which throws Throwable.
  • This method gets executed before object is getting garbage collected.
  • It gives chance to release allocated resources by an object.

No comments:

Post a Comment