简体   繁体   English

为什么局部变量是最终变量?

[英]Why local variables are final?

Why local variable make as final whether method argument or inside method. 为什么局部变量作为方法参数还是内部方法作为最终变量。

private void add(final int a , final int b) {
    final int c = 0;
}

Please anyone clarify.i am searching a lot but i did not find exact answer. 请任何人clarify.i正在搜索很多,但我没有找到确切的答案。

One reason is it prevents you inadvertently changing them. 原因之一是它可以防止您无意中更改它们。 It's good practise since it'll catch some hard-to-spot coding mistakes. 这是一个好习惯,因为它会遇到一些难以发现的编码错误。

The second reason is that if you're using inner classes, variables referenced from an outer scope need to be declared as final . 第二个原因是,如果您使用内部类,则需要将外部作用域引用的变量声明为final See this SO answer for more detail. 请参阅此SO答案以获取更多详细信息。

The problem with final is that it means different things in different contexts. final的问题在于,在不同的上下文中它意味着不同的事物。 See this discussion for more info. 有关更多信息,请参见此讨论

Functional style uses final variables. 功能样式使用最终变量。 This is one reason. 这是原因之一。 Another one is closures. 另一个是闭包。

Final variables are the only ones that can be used in closures . 最终变量是唯一可以在闭包中使用的变量。 So if you want to do something like this: 因此,如果您想执行以下操作:

void myMethod(int val) {
    MyClass cls = new MyClass() {
        @override
        void doAction() {
            callMethod(val);  // use the val argument in the anonymous class - closure!
        }
    };
    useClass(cls);
}

This won't compile, as the compiler requires val to be final. 这不会编译,因为编译器要求val是final。 So changing the method signature to 因此将方法签名更改为

void myMethod(final int val)

will solve the problem. 将解决问题。 Local final variable will do just as well: 局部最终变量也将执行以下操作:

void myMethod(int val) {
    final int val0;
    // now use val0 in the anonymous class

final in these instances simply means that the values cannot be changed. 在这些情况下,final仅表示无法更改值。 Trying to set another value to any of your final variables will result in a compile-time error 尝试为您的任何最终变量设置另一个值将导致编译时错误

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM