Within a class, the order of initialization is determined by the order that the variables are defined within the class. The variable definitions may be scattered throughout and in between method definitions, but the variables are initialized before any methods can be called—even the constructor.

解决方案 »

  1.   

    static 类型的对象只在第一次使用时初始化一次,以后你每实例化一个aa 类时
    static Test1 k = new Test1();//这条语句将不会再执行
    因为它是静态的,已经驻留在内存中
      

  2.   

    yoken:感谢您对这个问题的答复。对您的答复我还在理解中,目前还没有理解好。这段代码的输出我实在无法理解,尽管我刚刚通过了SCJP考试。希望您或其他朋友能再详细讲解一下。
      

  3.   

    one_bird:您好,感谢您对这个问题的答复。您说的静态对象初始化一次,这点我是知道的。但是我还是不清楚“为什么程序的第一行输出是aa2”。如能再详细讲解一下,将不胜感激。
      

  4.   

    这是因为:当class具有static field,且直接在宣告处透过「=...」的方式设定其
    值时,
    编译器会自动将这些叙述依序搬到class constructor内。同样地,当class具有instancefield,且直接在宣告处透过「=...」的方式设定其值时,编译器会自动将这些叙述
    依序搬
    到instance constructor内。而对于class constrcutor,把其他static字段搬入内的次序依声明次序依次加入。对于instance constructor,也会加入各个sinstance field,但其次序是先所有的instance field,最后为instance constructor。
      

  5.   

    第一行肯定是输出aa2“Java尽自己的全力保证所有变量都能在使用前得到正确的初始化” 所以在aa的初始化过程中,必须要先对Test1初始化。而test1初始化中又需要对aa进行调用。所以每次aa new 一下会 打印出 aa(m) 于是打印了aa2,aa4。而static 的驻留内存。
    当Test1()构造完毕时候开始显示了。 所以先打印TestCons, 然后依次打印出几个static 到这里知识对aa() 初始化完毕。。 并且所有的static 不再被打印。
    于是开始执行Test1 的main
    打印MainBegins 再次构造Test1.
    aa2 aa4被打印。
      

  6.   

    static aa a = new aa(1);
    -->
    static Test1 k = new Test1();
         -->
         aa b = new aa(2); (System.out.println ("aa"+m);)
         -->
         aa d = new aa(4); (System.out.println ("aa"+m);)
         -->
         System.out.println ("Test1Cons");
          -->
         aa a = new aa(1); (System.out.println ("aa"+m));
    -->
     System.out.println ("MainBegin");
    new Test1();
       -->aa b = new aa(2);
       -->aa d = new aa(4);
       -->System.out.println ("Test1Cons");    -->
         static aa c = new aa(3); (System.out.println ("aa"+m));
      

  7.   

    moumouren(某某人):感谢您的答复.您回答中,aa3输出顺序错误,同时漏了静态块的输出。不过您前面的顺序是我需要的,我的疑惑点在那里。
      

  8.   

    feiyuegaoshan(飞跃):感谢您的答复。您的答复对我的理解有很大启发。
      

  9.   

    totodo(是时候了,小土豆仙) :感谢您的答复。您的答复正是我需要的。非常感谢!
      

  10.   

    tyrone98(林林) :是为了考试,不是为了开发。考试——把考生当成编译器。明白了?