静态块内部声明的静态变量与java中静态块外部的差异

时间:2013-08-11 18:21:15

标签: java static

  1. 静态块外部声明的静态变量与静态块内声明的变量之间有什么区别? (考虑代码段)
  2. 代码段如下:

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

2 个答案:

答案 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
}