为什么final是Java中局部变量的唯一修饰符? [英] Why is final the only modifier for local variables in Java?

查看:140
本文介绍了为什么final是Java中局部变量的唯一修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Test {

    public static void main(String[] args) {
        private int x = 10;
        public int y = 20;
        protected int z = 30;
        static int w = 40;  
        final int i = 50;
    }
}

唯一适用的修饰符是最终的这里; 对于其他修饰符,程序会提供编译器错误。这是为什么?请详细解释。

The only applicable modifier is final here; for other modifiers, the program gives compiler errors. Why is that? Please explain in detail.

推荐答案

简而言之 - 在这种情况下,其他任何修饰语都没有意义。说变量是 public private protected ,或者 static 一旦方法退出,在局部变量的上下文中就没有意义了,这个变量将超出范围(并被垃圾收集)。这些修饰符用于类字段(和方法),以定义它们的可见性(或者在 static 的情况下,它们的范围)。

In short - none of the other modifiers make sense in that context. Saying a variable is public, private, protected, or static simply doesn't make sense in the context of a local variable that will go out of scope (and be garbage collected) once the method exits. Those modifiers are intended for class fields (and methods), to define their visibility (or in the case of static, their scope).

final 是唯一一个在局部变量的上下文中有意义的因为它意味着该变量不能在初始声明后进行修改,它与访问控制无关。

final is the only one that makes sense in the context of a local variable because all it means is that the variable cannot be modified after its initial declaration, it has nothing to do with access control.

这篇关于为什么final是Java中局部变量的唯一修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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