Possible Duplicate:
Why would one mark local variables and method parameters as “final” in Java?
I was checking some Java code, I am not good at java at least have some knowledge what final does such as sealed classes, readonly fields and non-overridable methods but this looks weird to me, declaring a variable final
in methods:
private static void queryGoogleBooks(JsonFactory jsonFactory, String query) throws Exception {
// Set up Books client.
final Books books = Books.builder(new NetHttpTransport(), jsonFactory)
.setApplicationName("Google-BooksSample/1.0")
.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
@Override
public void initialize(JsonHttpRequest request) {
BooksRequest booksRequest = (BooksRequest) request;
booksRequest.setKey(ClientCredentials.KEY);
}
})
.build();
Could you tell me what the meaning of final
is in this context?
Here is the complete code:
http://code.google.com/p/google-api-java-client/source/browse/books-cmdline-sample/src/main/java/com/google/api/services/samples/books/cmdline/BooksSample.java?repo=samples
It simply makes the local variable books
immutable. That means it will always be a reference to that same Book
object being created and built, and cannot be changed to refer to another object, or null.
The Book
object itself is still mutable as can be seen from the sequence of accessor calls. Only the reference to it is not.
In this case, final Books books
simply means that books
must be assigned a value exactly once.
I like to use the final
keyword like this as it shows intent of the variable, which I find to be valuable information when looking at code as it removes yet another variable from the situation...so to speak.
If I don't mark a variable as final
then it stands out as something to keep my eye on because it's going to change values sometime soon. This information is helpful while, for example, stepping through the code in the debugger or refactoring & moving around code.
- For further reading on all things
final
: The Final Word On the final Keyword
This likewise makes the variable reference read-only. Usually, this is to protect the code from accidentally modifying a variable that must not change.
I'm pretty sure it means nothing more than the variable books cannot be overwritten later on in the method.
This code is using anonymous class JsonHttpRequestInitializer, where it refers to the local variable in method queryGoogleBooks, the problem in this kind of situation is that the queryGoogleBooks method could return before initialize method of the JsonHttpRequestInitializer is completed, where it could cleanup the variable and could cause the initialize method of JsonHttpRequestInitializer to fail. So it is required to declare the variables as final in this type of situations. For more details refer to,
Cannot refer to a non-final variable inside an inner class defined in a different method