Java中方法的最终变量 [英] final variable in methods in Java

查看:153
本文介绍了Java中方法的最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么将局部变量和方法参数标记为final”在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?

这是完整的代码:

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

推荐答案

简单来说使局部变量 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆