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'?

4

2 回答 2

9
 static int i = 10;      //line 1  

这里变量的范围i是类级别的。您可以在类内的任何地方访问它。

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

这里变量的范围i仅限于静态块(如循环变量)。您不能从外部块访问它。

于 2013-08-11T18:26:12.003 回答
0

在我看来

第 1 行中的“i”是全局变量,但在第 2 行中它是局部变量,也就是说您无法访问超出其范围的变量(这也是问题 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
}
于 2013-08-11T18:45:40.407 回答