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

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

    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.

提交回复
热议问题