初始化一个对象时是按这样的顺序进行的:
1、所有数据域被初始化为默认值(0, false, null)
2、按照在类声明中出现的顺序依次执行所有的域初始语句或初始化块,静态域的初始化要早于实例域的初始化
3、如果构造器第一行调用了第二个构造器,则执行第二个构造器,以此类推
4、执行这个构造器的主体
具体看下面的注释:- class Bowl{
- Bowl(int marker){
- System.out.println("Bowl(" + marker + ")");
- }
- void f1(int marker){
- System.out.println("f1(" + marker + ")");
- }
- }
- class Table{
- static Bowl bowl1 = new Bowl(1); //按照声明顺序 bowl1的初始化早于bowl2的初始化,然后才是Table()构造函数
- Table(){
- System.out.println("Table()");
- bowl2.f1(1);
- }
- void f2(int marker){
- System.out.println("f2(" + marker + ")");
- }
- static Bowl bowl2 = new Bowl(2);//(2)
- }
- class Cupboard{
- Bowl bowl3 = new Bowl(3);//静态域的初始化要早于实例域并且按照声明顺序,
- //那么先初始化bowl4再初始化bowl5,再初始化bowl3,接着才是构造方法
- static Bowl bowl4 = new Bowl(4);
- Cupboard(){
- System.out.println("Cupboard()");
- bowl4.f1(2);
- }
- void f3(int marker){
- System.out.println("f3(" + marker + ")");
- }
- static Bowl bowl5 = new Bowl(5);
- }
- public class StaticInitialization {
- public static void main(String[] args) {
- System.out.println("Creating new Cupboard() in main");
-
- new Cupboard();
-
- System.out.println("Creating new Cupboard() in main");
- new Cupboard();
-
- table.f2(1);
- cupboard.f3(1);
-
- }
- static Table table = new Table();
- static Cupboard cupboard = new Cupboard();
- }
复制代码 |