for instance:public class StaticInitDemo {static int i = 5;
  static {
    System.out.println("Static code i= "+ i++ );
  }
}
public class Test {
  public static void main(String args[]) {
    System.out.println("Main code: i="
      + StaticInitDemo.i);
  }
}将打印出:
Static code: i=5
Main code: i=6

解决方案 »

  1.   

    你的第一个例子会编译通过吗?
    public class A
    {
      static int a=9;
      static {
            a=4;
    }
    }
    public class b
    {
       A s=new A();
       System.out,println(a); 
    ]我认为会出错啊
      

  2.   

    运行了一下,真是这样,只能说明static变量赋值是按顺序执行的罢?
      

  3.   

    这种程序,一个文件里两个public class,没有main(),编译是通不过的。
      

  4.   

    其实我相信楼主想问的是各个类型宣称的初始化顺序,请看Order of code execution (when creating an object) is a bit tricky.
    1. static variables initialization.
    2. static initializer block execution. (in the order of declaration, if multiple blocks found)
    3. constructor header ( super or this – implicit or explicit )
    4. instance variables initialization / instance initializer block(s) execution
    5. rest of the code in the constructor
      

  5.   

    class A{
        static {
            a=4;
           System.out.println(a);//加上这句
        }
        static int a=9;
    }编译报错: illegal forward reference
    那为什么a=4可以.....召唤达人。
      

  6.   

    to 石头:
    这是因为
    In all the initializers, forward referencing of variables is not allowed. Forward referencing of methods is allowed.
      

  7.   

    1,2有什么想不通的,后入为主,如果不明白static{} 请参考其他帖子或书籍