日期:2014-05-20  浏览次数:20787 次

static 加载的先后顺序???
1.eg:
static   int   x   =     y;
  static   int   y   =5;

编译错误,变量的提前引用.                 i   know.

2.eg:
static   int   x   =   returnY();
static   int   y   =   5;
static   int   returnY(){
              return   y;
    }

public   static   void   main(String[]   args){

        System.out.println(x);
}

now   x   is   a   number     0   ;         //   why   is   0??   and   why   not   a   compile   error??

3.eg:

static   int   y   =   5;       //   提上前了.
static   int   x   =   returnY();

static   int   returnY(){
              return   y;
    }

public   static   void   main(String[]   args){

        System.out.println(x);
}

now   x   is   a   number     5;    


------解决方案--------------------
lz这个实验本身就可以说明一些问题了吧。


应该是在程序加载的时候,static就被负值了。

static再怎么样肯定也是有个顺序的。

所以出现2和3 的区别阿



------解决方案--------------------
在2中,执行static int x = returnY();时候会调用静态方法
static int returnY(){
return y;
}
但此时y还没有赋值,就返回int型(y是int型)的默认值0.所以输出的是0.


------解决方案--------------------
y已经初始化,但还没有赋值。建议不要根据这种测试来写代码,因为不同JVM的实现是不可控的,最后以明确的方式来写。
------解决方案--------------------
貌似是从上到下的执行。。。
------解决方案--------------------
请参考关于:类的初始化
------解决方案--------------------
可以读读《深入Java虚拟机》。