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
If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses.
You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses.
4. Final Variables. Variables marked as final can't be reassigned. Once a final variable is initialized, it can't be altered.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With