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...
{
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...
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.
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()构造函数
.................不知道这样说你明白了没有?