在学习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
此时结果又为什么变成了这样呢?当我将注解中的语句和前边的替换以后也是这个结果,为什么呢?
*/

解决方案 »

  1.   

    感觉你好像把两个类的成员变量搞混了
    我理解的你上面三种情况分别是这样:
    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
      

  2.   

    think in java 中说到,静态成员只在第一次调用的时候初始化
      

  3.   

    首先你要知道你想干什么。你的第一例中,Test1中定义不定义a、b,和Test1()构造器中的Test.a++;有关系吗?你操作的Test又不是Test1的东西。(最好改类名,差别大点)。你的第二例:Test1对Test 没有任何影响。
      

  4.   

    按照你的想法
    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
      

  5.   

    不是说static数据存储在同一块区域吗 ?那个a,b存储在同一块区域了,应该有影响了吧
      

  6.   


    public class Test1{
        static int a = 6;
        static int b = 5;
        public Test1() {
            Test.a = a++;
            Test.b = b++;
        }
    }我写的是Test.a++不是Test.a = a++
      

  7.   

    yqj2065 可以私信你吗 我不清楚