在Java中,在静态块内声明的静态变量和在静态块外声明的静态变量有什么区别?

3
  1. 在静态块外声明的静态变量和在静态块内声明的变量有什么区别?(考虑以下代码段)

代码段如下:

class A{

    static int i = 10;      //line 1

    static { int i = 20;}   //line 2

    public static void main(String[] args) {
        System.out.println(A.i); //output is 10
    }
}

2.如何访问第2行的变量'i'?


5
看起来像是作业,但无论如何,请展示一下您对答案的想法。 - Hovercraft Full Of Eels
2
区别在于一个的范围比另一个更广,仅此而已。 - Peter Lawrey
为什么它不会报错,因为两者都是静态的,并且具有相同的名称,即“i”? - chathura
@chathura2020 这是你的作业任务吗?只是复制粘贴而已,有点懒哦。 - darrengorman
"static { }" 并不是声明静态变量的语句,实际上它是一种允许初始化静态变量的方法。和任何方法一样,在静态初始化方法中声明的变量只在该方法内部有效。 - Hot Licks
2个回答

9
 static int i = 10;      //line 1  

这里变量i的作用域在类级别。您可以从类内的任何地方访问它。

static { int i = 20;}   //line 2

这里变量i的作用域仅限于静态块中(就像循环变量一样)。你不能从块外部访问它。


正确,但最好在回答之前看到原帖作者发表自己的想法。 - darrengorman

0

In my opinions

"i" in Line 1 is a global variable,but in Line 2 it is local,that is to say you can't access variable out of it's scope(also this is the answer for question 2)

static {
    int i = 10;
    // this variable's scope only in static {},out of {},you can't access
    // so, if you want access a variable declared in a it's part,you must hold it's refer
    // but, if do this,why not declared it as a class instance member variable or static member variable(just like line 1)
    // generally,static code block is used in initial some class variable or do some prepare work when ClassLoader load it
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接