Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final variable in methods in Java [duplicate]

Tags:

java

final

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

like image 480
Tarik Avatar asked Nov 29 '11 05:11

Tarik


People also ask

What happens if a method has the final keyword as modifier?

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.

What happens if a method is made final?

You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses.

Can a final variable be reassigned?

4. Final Variables. Variables marked as final can't be reassigned. Once a final variable is initialized, it can't be altered.


1 Answers

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.

like image 101
BoltClock Avatar answered Sep 21 '22 13:09

BoltClock