class Tag
{
Tag(int er)
{
System.out.println ("Tag("+er+")");
}
}class Card
{
Tag t1=new Tag(1);
Card()
{
System.out.println ("Card()");
t3=new Tag(33);
}

Tag t2=new Tag(2);

void f()
{
System.out.println ("f()");
}

Tag t3=new Tag(3);
}public class orderofInitialization
{
public static void main(String[] args)
{
Card t=new Card();
t.f();
}
}这个程序在main里对t.f()进行了调用,但是上面的默认的构造函数应该是自动调用的,第一个是把1传给了Tag(int er),打印出Tag(1),第二个应该调用Card()吧,但是他却调用的是Tag t2=new Tag(2),打印的却是Tag(2),下面也一样,我知道我理解错了,你们能讲一下吗,什么原因?是个什么样的调用顺序?下面是执行后的结果:Tag(1)
Tag(2)
Tag(3)
Card()
Tag(33)
f()
Press any key to continue...

解决方案 »

  1.   

    《Thinking In Java》:
    Order of initializationWithin 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.
      

  2.   

    谢谢楼上,这到题就是thinking in java 3rd上的题目,你说先是变量,后是构造函数,在那个程序中输出的第一个是Tag(1),确实是构造函数,但是这个构造函数是在第二个类中创建的,然后下面是第二个类的构造函数,为什么他不执行第二个类的构造函数,而执行第二个类下面的第一个构造函数呢?同样是构造函数,我觉得还是有顺序的.请指点!
      

  3.   

    执行的时间是这样的:
    1.在main()函数中:Card t=new Card();
    2.开始对类Card进行初始化,先从变量t1开始:
    Tag t1=new Tag(1);在Tag类中以“先是变量,接着是构造函数,然后是一般函数”的顺序对Tag对象t1进行初始化;Tag类没有变量,只有一个构造函数,所以执行Tag(i);
    3.同理,随后依次执行:Tag t2=new Tag(2);Tag t3=new Tag(3);//都是变量
    4.Card对象中,变量初始化完后,才进入Card()构造函数
    .................不知道这样说你明白了没有?