在学习java的静态变量初始化的时候看到了下面的例子,搞得有点迷茫
第一例:
public class Test
{
public static Test1 t = new Test1();
public static int a = 3;
public static int b;
public static void main(String[] arg)
{
System.out.println(Test.a);
System.out.println(Test.b);
}
}
class Test1
{
//static int a = 6;
//static int b = 5;
public Test1()
{
Test.a++;
Test.b++;
}
}
/*
结果:
3
1
这个我能够理解,然后我将Test中的注解那句加上以后,结果为什么依然没有变化
据我自己分析t,a,b的值先分别初始化为默认初始值null,0,0,然后在将 new Test1()赋值给t,然后对Test1进行初始化,因为a,b是静态变量,所以不要在创建了,此时就直接将6赋值给a,5赋值给b,然后再执行构造函数,所以a的值变化顺序是a->0->6->7->3
b->0->5->6 不知道哪个地方分析错误了*/
接着我又进行了一些变化
public class Test
{
public static Test1 t = new Test1();
public static int a = 3;
public static int b;
public static void main(String[] arg)
{
System.out.println(Test.a);//替代前边的语句System.out.println(a);
System.out.println(Test.b);//替代前边的语句System.out.println(b);
}
}
class Test1
{
static int a = 6;
static int b = 5;
public Test1()
{
a++;
b++;
}
}
/*
结果:
3
0
此时结果又为什么变成了这样呢?当我将注解中的语句和前边的替换以后也是这个结果,为什么呢?
*/
第一例:
public class Test
{
public static Test1 t = new Test1();
public static int a = 3;
public static int b;
public static void main(String[] arg)
{
System.out.println(Test.a);
System.out.println(Test.b);
}
}
class Test1
{
//static int a = 6;
//static int b = 5;
public Test1()
{
Test.a++;
Test.b++;
}
}
/*
结果:
3
1
这个我能够理解,然后我将Test中的注解那句加上以后,结果为什么依然没有变化
据我自己分析t,a,b的值先分别初始化为默认初始值null,0,0,然后在将 new Test1()赋值给t,然后对Test1进行初始化,因为a,b是静态变量,所以不要在创建了,此时就直接将6赋值给a,5赋值给b,然后再执行构造函数,所以a的值变化顺序是a->0->6->7->3
b->0->5->6 不知道哪个地方分析错误了*/
接着我又进行了一些变化
public class Test
{
public static Test1 t = new Test1();
public static int a = 3;
public static int b;
public static void main(String[] arg)
{
System.out.println(Test.a);//替代前边的语句System.out.println(a);
System.out.println(Test.b);//替代前边的语句System.out.println(b);
}
}
class Test1
{
static int a = 6;
static int b = 5;
public Test1()
{
a++;
b++;
}
}
/*
结果:
3
0
此时结果又为什么变成了这样呢?当我将注解中的语句和前边的替换以后也是这个结果,为什么呢?
*/
我理解的你上面三种情况分别是这样:
1.Test.a>0>1>3 Test.b>0>1
2.Test.a>0>1>3 Test.b>0>1
t.a>0>6 t.b>0>5
3. Test.a>0>3 Test.b>0>0
t.a>0>6>7 t.b>0>5>6
package semantics.staticDemo;
public class Test{
public static Test1 t = new Test1();
public static int a = 3;
public static int b; public static void main(String[] arg) {
System.out.println(Test.a);
System.out.println(Test.b);
}
}public class Test1{
static int a = 6;
static int b = 5;
public Test1() {
Test.a = a++;
Test.b = b++;
}
}
输出3 5
public class Test1{
static int a = 6;
static int b = 5;
public Test1() {
Test.a = a++;
Test.b = b++;
}
}我写的是Test.a++不是Test.a = a++