Why is final the only modifier for local variables in Java?

前端 未结 3 822
無奈伤痛
無奈伤痛 2020-12-29 13:51
class Test {

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


        
3条回答
  •  伪装坚强ぢ
    2020-12-29 14:56

    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 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.

提交回复
热议问题