Friday 21 February 2014

Final In Java

Final is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to re-initialized final variables in java.
 

Final and Immutable Class in Java

 
Final keyword helps to write immutable class. Immutable classes are the one which can not be modified once it gets created and String is primary example of immutable and final class . Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead. You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java.

Important points on final in Java


1. Final keyword can be applied to member variable, local variable, method or class in Java.

2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration.

5. Only final variable is accessible inside anonymous class in Java
 
6. Final method can not be overridden in Java.

7. Final class can not be inheritable in Java.

8. Final is different than finally keyword which is used on Exception handling in Java.
 
9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.
 
10. All variable declared inside java interface are implicitly final.

11. Final and abstract are two opposite keyword and a final class can not be abstract in java.
 
12. Final methods are bonded during compile time also called static binding.


13. Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".


14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.

15. As per Java code convention final variables are treated as constant and written in all Caps e.g.


private final int COUNT=10;

16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:

private final List Loans = new ArrayList();
list.add(“home loan”);  //valid
list.add("personal loan"); //valid
loans = new Vector();  //not valid

 

No comments:

Post a Comment