Java中方法的最终变量 [英] final variable in methods in Java
问题描述
我正在检查一些Java代码,我不擅长java至少有一些知识,比如密封类,只读字段和不可覆盖的方法,但这对我来说很奇怪,在方法中声明变量 final
:
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?
这是完整的代码:
推荐答案
简单来说使局部变量 books
不可变。这意味着它将永远是对同一个 Book
对象的引用,并且不能更改为引用另一个对象,或者为null。
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.
从访问者调用序列可以看出, Book
对象本身仍然是可变的。只有它的引用不是。
The Book
object itself is still mutable as can be seen from the sequence of accessor calls. Only the reference to it is not.
这篇关于Java中方法的最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!