static都是在载入时执行的, 所以上面即使main方法为空还是会执行, public static int i;使得i=0; public static int j = ++i;使得j=0; public static Teste e = new Teste(); 则是要执行 public Teste() { System.out.println(j); } 所以当然是0啦.
上面有错, 所有static按顺序执行: 1、public static int i;使得i=0; 2、public static Teste e = new Teste(); static的变量都赋以0,所以输出0; 3、public static int j = ++i; 如果你改成: public static int i; public static int j = 1; public static Teste e = new Teste(); 就会输出1了。
能说一下执行步骤吗? 执行到public static Teste e = new Teste(); 后怎么执行?对于楼主的程序.
public static Teste e = new Teste(); public static int j = ++i; 这两句需要换下位置
当类被载入内存时,会先为其成员配置空间,并将基本成员设为默认值,reference设为null,然后执行初始化动作。 public class Teste { //i:0 , e : null, j :0 public static int i; //i :0, e: null, j : 0 public static Teste e = new Teste(); //goto label A
B:public static int j = ++i; //j:1; public Teste() { //j: 0 A:System.out.println(j); //goto label B } public static void main(String[] args) { } }
所以上面即使main方法为空还是会执行,
public static int i;使得i=0;
public static int j = ++i;使得j=0;
public static Teste e = new Teste();
则是要执行
public Teste() {
System.out.println(j);
}
所以当然是0啦.
所有static按顺序执行:
1、public static int i;使得i=0;
2、public static Teste e = new Teste();
static的变量都赋以0,所以输出0;
3、public static int j = ++i;
如果你改成:
public static int i;
public static int j = 1;
public static Teste e = new Teste();
就会输出1了。
执行到public static Teste e = new Teste();
后怎么执行?对于楼主的程序.
public static int j = ++i;
这两句需要换下位置
public class Teste
{
//i:0 , e : null, j :0
public static int i;
//i :0, e: null, j : 0
public static Teste e = new Teste();
//goto label A
B:public static int j = ++i;
//j:1;
public Teste()
{
//j: 0
A:System.out.println(j);
//goto label B
} public static void main(String[] args)
{ }
}