Possible Duplicate:
When to use final
What is the use of declaring final keyword for objects? For example:
final Object obj = new myclass();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using the “final” keyword makes the the variable you are declaring immutable. Once initially assigned it cannot be re-assigned.
However, this does not necessarily mean the state of the instance being referred to by the variable is immutable, only the reference itself.
There are several reasons why you would use the “final” keyword on variables. One is optimization where by declaring a variable as final allows the value to be memoized.
Another scenario where you would use a final variable is when an inner class within a method needs to access a variable in the declaring method. The following code illustrates this:
If x is not declared as “final” the code will result in a compilation error. The exact reason for needing to be “final” is because the new class instance can outlive the method invocation and hence needs its own instance of x. So as to avoid having multiple copies of a mutable variable within the same scope, the variable must be declared final so that it cannot be changed.
Some programmers also advocate the use of “final” to prevent re-assigning variables accidentally where they should not be. Sort of a “best practice” type rule.