在创建阶段系统通过下面的几个步骤来完成对象的创建过程

  • 为对象分配存储空间
  • 开始构造对象
  • 从超类到子类对static成员进行初始化
  • 超类成员变量按顺序初始化,递归调用超类的构造方法
  • 子类成员变量按顺序初始化,子类构造方法调用

本文重点演示第三步到第五步:

Grandpa类

 1 package com.xinye.test;
 2 
 3 public class Grandpa {
 4     {
 5         System.out.println("执行Grandpa的普通块");
 6     }
 7     static {
 8         System.out.println("执行Grandpa的静态快");
 9     }
10     public Grandpa(){
11         System.out.println("执行Parent的构造方法");
12     }
13     static{
14         System.out.println("执行Grandpa的静态快222222");
15     }
16     {
17         System.out.println("执行Grandpa的普通快222222");
18     }
19 }

Parent类

 1 package com.xinye.test;
 2 
 3 public class Parent extends Grandpa{
 4     protected int a = 111;
 5     {
 6         System.out.println("执行Parent的普通块");
 7     }
 8     static {
 9         System.out.println("执行Parent的静态快");
10     }
11     public Parent(){
12         System.out.println("执行Parent的构造方法");
13     }
14     public Parent(int a){
15         this.a = a ;
16         System.out.println("执行Parent的构造方法:InitParent(int a)");
17     }
18     static{
19         System.out.println("执行Parent的静态快222222");
20     }
21     {
22         System.out.println("执行Parent的普通快222222");
23     }
24 }

Child类

 1 package com.xinye.test;
 2 
 3 public class Child extends Parent {
 4     {
 5         System.out.println("执行Child的普通块");
 6     }
 7     static {
 8         System.out.println("执行Child的静态快");
 9     }
10     public Child(){
11         super(222);
12         System.out.println("a = " + a);
13         System.out.println("执行Child的构造方法");
14     }
15     static{
16         System.out.println("执行Child的静态快222222");
17     }
18     {
19         System.out.println("执行Child的普通快222222");
20     }
21 }

测试类

 1 package com.xinye.test;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         /**
 7          * 
 8          *  第一步:
 9          *      Grandpa如果有静态块,按照Grandpa的静态块声明顺序依次执行
10          *      Parent中如果有静态块,按照Parent中的静态块声明顺序依次执行
11          *      Child中如果有静态块,按照Child中的静态块声明顺序依次执行
12          *  第二部:
13          *      如果Grandpa中有普通块,按照Grandpa的普通块声明顺序依次执行
14          *          执行完毕后,执行被调用的构造方法(如果Parent调用了Grandpa中的特定构造;如果没有则调用默认构造)
15          *      如果Parent中有普通块,按照Parent的普通块的声明顺序依次执行
16          *          执行完毕后,执行被调用的构造方法(如果Child调用了Parent的特定构造;如果没有则调用默认构造)
17          *         如果Child中有普通块,按照Child的普通块的声明顺序依次执行
18          *             执行完毕后,执行被客户端调用的特定构造方法
19          */
20         
21         new Child();
22     }
23 }

执行结果

 1 执行Grandpa的静态快
 2 执行Grandpa的静态快222222
 3 执行Parent的静态快
 4 执行Parent的静态快222222
 5 执行Child的静态快
 6 执行Child的静态快222222
 7 执行Grandpa的普通块
 8 执行Grandpa的普通快222222
 9 执行Parent的构造方法
10 执行Parent的普通块
11 执行Parent的普通快222222
12 执行Parent的构造方法:InitParent(int a)
13 执行Child的普通块
14 执行Child的普通快222222
15 a = 222
16 执行Child的构造方法

 

posted on 2014-08-13 16:40  wangwangheng  阅读(2615)  评论(1编辑  收藏  举报