代码段如下:
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'?
答案 0 :(得分:9)
static int i = 10; //line 1
此处变量i
的范围是在类级别。您可以从类中的任何位置访问它。
static { int i = 20;} //line 2
此处变量i
的范围仅限于静态块(如循环变量)。您无法从外部块访问它。
答案 1 :(得分: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
}