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

前端 未结 3 821
無奈伤痛
無奈伤痛 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:53

    Consider that all those declarations are local variable declarations.

    For some more details, always go to the Java Language Specification which states a local variable can be made up of

    LocalVariableDeclarationStatement:
        LocalVariableDeclaration ;
    
    LocalVariableDeclaration:
        VariableModifiersopt Type VariableDeclarators
    

    where

    VariableModifiers:
        VariableModifier
        VariableModifiers VariableModifier
    
    VariableModifier: one of
        Annotation final
    
    VariableDeclarators:
        VariableDeclarator
        VariableDeclarators , VariableDeclarator
    
    VariableDeclarator:
        VariableDeclaratorId
        VariableDeclaratorId = VariableInitializer
    
    VariableDeclaratorId:
        Identifier
        VariableDeclaratorId []
    
    VariableInitializer:
        Expression
        ArrayInitializer
    

    So the only acceptable VariableModifier is final (and an annotation, which is rare).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-29 14:56

    I believe it's because the other modifiers apply to classes rather than methods.

    A private, protected or public modifier affects the visibility of global variables to objects of other classes, so using those modifiers for local variables is non-sensical.

    A static modifier declares a global variable to belong to a class rather than objects of a class, so using them for local variables does not make sense either.

    The only modifier that makes sense is "final", which ensures a local variable does not change within the method.

    0 讨论(0)
提交回复
热议问题