62,616
社区成员
发帖
与我相关
我的任务
分享
public class Test1 {
public static Test1 t = new Test1();
public static int a;
public static int b = 0;
Test1(){
a++;
b++;
}
public void printAB() {
System.out.println(a + ","+b);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test1().printAB();
}
}
public class Test
{
//1
public static Test t = new Test();
//2
public static int a;
//3
public static int b = 0;
//4
Test(){
a++;
b++;
}
public void printAB() {
System.out.println(a + ","+b);
}
/**
* @param args
*/
public static void main(String[] args) {
/*
* 这句话执行的顺序是 1、4、2、3、4
*/
new Test().printAB();
}
}
JVM会在类加载完成后,给static变量分配内存地址和初始化默认值(只是初始化默认值,而不是赋值);
当类被首次主动(类似于 创建类的实例,调用类的静态方法)使用时进行初始化,此时的初始化是指按照开发人员定义的值进行赋值 也就是 “=”号右边的值
也就是说 当 第1、4执行完后 a=1,b=1 然后执行2的时候 由于没有=号 所以不会赋值 a还是=1,执行3的时候 将b值赋值为0 所以再 执行4时 a 等于2 b等于 1
public class Test1 {
public static int a;
public static int b = 0;
public static Test1 t = new Test1();
Test1(){
a++;
b++;
}
public void printAB() {
System.out.println(a + ","+b);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test1().printAB();
}
}