简体   繁体   English

局部变量在类的方法中成为final-但是为什么呢?

[英]local variable made final in method of a class — but why?

Today while searching for a certain piece of code from google, I came across one Q/A blog, where its been said that we can declare a local variable inside a method of a class to be final. 今天,当我从Google搜索某段代码时,我遇到了一个Q / A博客,据说我们可以在类的方法内声明一个局部变量为final。 However, the author was reluctant enough to explain the need/ benefit of doing so. 但是,作者不愿解释这样做的必要性/好处。

like 喜欢

public class A
{
 private void show()
 {
  final String s="checking";
 }
}

I would seek java gurus' help to educate me on this. 我会寻求Java专家的帮助来对此进行教育。 Thanks in advance for your kind support and guidance. 在此先感谢您的支持和指导。

Best regards! 最好的祝福!

In addition to other answers, making a variable final enables the use of that variable in inline implementation of classes and interfaces: 除了其他答案外,将变量设为final可以在类和接口的内联实现中使用该变量:

final String test = "test";

foo = new Foo() {
        public void bar() {
            System.out.println(test);
        }
    };

EDIT: If you are a beginner it might also be worth pointing out that the variable is in fact a reference to an instance . 编辑:如果您是初学者,可能还应该指出该变量实际上是 实例引用 When you make a variable final you are in fact making the reference constant, that is, a final variable can never refer to some other instance after initialization. 当将变量定为final时,实际上是使引用成为常数,也就是说,final变量在初始化后永远不能引用其他实例。 This makes no claims as to whether the actual referenced instance is constant. 这没有要求实际引用的实例是否恒定。

For example, if you say final String[] foo = { "bar", baz" } you can do foo[0] = "sheep" even though foo is final . What you cannot do is reference foo variable to something else, like in foo = new String[]... or foo = someOtherArray . This has to do with mutability and immutability and those concepts are somewhat akin to final , so they might be worth some investigating. 例如,如果您说final String[] foo = { "bar", baz" } ,即使foofinal final String[] foo = { "bar", baz" }可以执行foo[0] = "sheep" 。您不能做的就是将foo变量引用到其他内容,例如在foo = new String[]...foo = someOtherArray ,这与可变性不可变性有关 ,这些概念有点类似于final ,因此可能值得研究。

The variable can be placed in read-only memory, making it faster to operate on. 该变量可以放置在只读存储器中,从而使其操作起来更快。

Also it can simply be logical to do so, for instance for representing local constants or ensuring that a certain value is not accidentally changed. 这样做也很简单,例如代表局部常数或确保某个值不会意外更改。 This makes it a useful way to turn bugs into compiler errors. 这使其成为将错误转化为编译器错误的有用方法。

Also, it allows for the variable to be used within inner/anonymous classes, as pointed out by the other answers. 另外,如其他答案所指出的,它允许在内部/匿名类中使用变量。

Apart from enforcing the variable to remain unchanged after its initialization, declaring a variable as final makes it accessible to the method local inner classes. 除了强制变量在初始化之后保持不变之外,将变量声明为final可以使方法局部内部类可以访问它。
More detailed information can be obtained by looking at the Disassembled code for the following small piece of code: 通过查看以下几小段代码的反汇编代码,可以获得更详细的信息:

class MyFinal 
{
    public static void main(String[] args) 
    {
        String str = "java";
        final String str1 = "Hello";
    }
}

The disassembled code for the above program is as follows: 上面程序的反汇编代码如下:

J:\>javap -c MyFinal
Compiled from "MyFinal.java"
class MyFinal extends java.lang.Object{
MyFinal();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   ldc     #2; //String java
   2:   astore_1
   3:   return

}

In main method of above disassembled code we see that , the java compiler has kept the code for String object creation of non-final variable str but it has silently omitted the String object creation code for final String str1 = "Hello"; 在上面的反汇编代码的主要方法中,我们看到,java编译器保留了用于non-final变量str的String对象创建的代码,但它默默地省略了用于final String str1 = "Hello";的String对象创建代码final String str1 = "Hello"; . It is so because, str1 is not used in the method anywhere. 之所以这样,是因为在任何方法中都没有使用str1 Hence it helps compiler to optimize the code , which lead to avoidance of unnecessary object creation if there is no use of it. 因此,它可以帮助编译器优化代码,从而避免了不必要的对象创建(如果不使用它们的话)。

It makes sensee to be able to tell easily that the variable won't change. 能够轻松判断变量不会改变是有意义的。 If this is a primitive, you can consider the value being immutable, and if it is not, you now know that the value will always be the same instance (which state can be changed). 如果这是一个原语,则可以认为该值是不可变的,如果不是,则现在您知道该值将始终是同一实例(可以更改其状态)。

This is useful for readability of the program so that we are sure that the variable is never reassigned. 这对于提高程序的可读性很有用,因此我们确保永远不会重新分配变量。 It is also useful for anonymous functions, explained here: Why do we use final keyword with anonymous inner classes? 它对匿名函数也很有用,在这里解释: 为什么我们将final关键字与匿名内部类一起使用?

Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. final添加到所有不应该改变的事物上,只会缩小您(或下一个正在处理代码的程序员)会误解或滥用导致代码生成的思维过程的可能性。

Taken from this answer to a similar question. 这个答案中得到一个类似的问题。

when a var is final, you can't change it. 当var是最终变量时,您无法更改它。 that means - one mistake you can't do - or, if to be more precise, one logical mistake that will create a compiling error, and saving long debugging. 这意味着-一个您无法做的错误-或更准确地说,是一个逻辑错误,它将创建一个编译错误,并节省了长时间的调试。


not to be mixed up with a final class that you can't inherit from. 不要与您不能继承的final class混淆。


more data could be found in wikipedia 可以在Wikipedia中找到更多数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么非最终的“局部”变量不能在内部类中使用,而是封闭类的非最终字段可以? - Why a non-final “local” variable cannot be used inside an inner class, and instead a non-final field of the enclosing class can? 在 ArrayBlockingQueue 中,为什么要将 final 成员字段复制到本地 final 变量中? - In ArrayBlockingQueue, why copy final member field into local final variable? Java:为什么我不能在任何类中使用final来访问局部变量JPanel? - Java: Why could I access a local variable JPanel without final inside the anymous class? 从内部类内部访问的Java局部变量; 需要声明为final,为什么它可以在NetBeans中工作? - Java local variable accessed from within inner class; needs to be declared final, why it works in NetBeans? 为什么final类不能被继承,而final方法可以被继承? - Why can't a final class be inherited, but a final method can be inherited? 为什么Java中的最终实例类变量? - Why final instance class variable in Java? 为什么最终变量没有内部类就返回? - Why final variable return without inner class? 为什么在方法内部而不是在类内部需要final - Why is final needed inside a method but not inside a class 从匿名内部类访问外部类的最终局部变量 - Accessing outer class final local variable from anonymuos inner class 为什么需要在@Override [inner class]方法内将变量转换为最终数组? - Why do I need to transform variable into final array inside @Override[inner class] method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM