在java中使用最终局部变量 [英] Use of final local variables in java

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

问题描述

我想知道是否有使用最终局部变量的可用性。当继承进入图像时,无论如何都不会覆盖变量。例如,下面的简单代码

I was wondering is there any usability of using final local variables. Variables are not overridden anyway when inheritance comes into picture. For example a simple code as below

public static void main(String args[]) {
    final String data = "Hello World!";
    System.out.println(data);
}

示例非常简单,可能不是相关代码,但问题更通用。我已经看到了很多代码(所有代码都包含在main函数中,它们都有最终的局部变量)是否有任何可用性将局部变量声明为final,而不是它们不能在同一个函数中编辑?

The example is quite simple one and may not be a relevant code but the question is more generic.I have seen a lot of codes(all incorporated in main function which have final local variables) Is there any usability of declaring local variables as final other than that they cannot be edited in the same function itself?

推荐答案

首先,关于变量被覆盖的部分 - final 有两个截然不同的含义。对于类和方法,它是关于继承;对于变量,它是关于只读的。

Firstly, the part about variables being "overridden" - final has two very different meanings. For classes and methods, it's about inheritance; for variables it's about being read-only.

最终局部变量有一个重要的特征:它们可以用在本地(通常是匿名的)内部类中。非最终局部变量不能。根据我的经验,这是本地变量的 final 的主要用途。

There's one important "feature" of final local variables: they can be used in local (typically anonymous) inner classes. Non-final local variables can't be. That's the primary use of final for local variables, in my experience.

public void foo() {
    final String x = "hello";
    String y = "there";

    Runnable runnable = new Runnable() {
        @Override public void run() {
            System.out.println(x); // This is valid
            System.out.println(y); // This is not
        }
    };
    runnable.run();
}

请注意,作为一种风格,有些人喜欢使用 final 即使他们在本地内部类中捕获变量。我肯定会对 final 作为默认值感到满意,但是对于非最终的修饰符不同,但我发现在任何地方明确添加修饰符太过分散注意力。

Note that as a matter of style, some people like to use final even when they're not capturing the variable in a local inner class. I'd certainly be comfortable with final being the default, but a different modifier for "non-final", but I find that adding the modifier explicitly everywhere is too distracting.

这篇关于在java中使用最终局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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