我们先来看一个实例
class example {
private privateitem i=new privateitem();
static staticitem j=new staticitem();
public example() {
// TODO Auto-generated method stub
System.out.println("this is example");
}
}
class bigexample extends example {
public bigexample() {
// TODO Auto-generated constructor stub
System.out.println("this is bigexample");
}
}
class staticitem {
public staticitem() {
// TODO Auto-generated constructor stub
System.out.println("this is staticitem");
}
}
class privateitem {
public privateitem() {
// TODO Auto-generated constructor stub
System.out.println("this is privateitem");
}
}
public class test {
/**
* @param args
*/
private static bigexample item;
public static void main(String[] args) {
// TODO Auto-generated method stub
item = new bigexample();
}
}
结果是这样的:
this is staticitem
this is privateitem
this is example
this is bigexample
从这里我们可以看出,当构造一个对象时,会先去看一看这个类是否有基类,如果有基类就先去基类中去,但是假如到一个类中,可是现在我们想类中有字段和构造函数,这个顺序是什么尼?从上面我们可以看出是先初始化了字段,然后再调用构造函数,这个其实想想也是必要的,因为构造函数的功能就是初始化一些类中的东西,如何还没有初始化变量引用,那么构造函数就没法初始化了,下面我们总结一下流程:
1.先去看一下这个类,有没有基类,如果有基类就先构造基类
2.在一个类中先初始化变量,变量中先初始化静态变量,然后是普通变量,然后再调用构造函数。