Java对象创建阶段的代码调用顺序

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

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

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

Grandpa类

 package com.xinye.test;

 public class Grandpa {
{
System.out.println("执行Grandpa的普通块");
}
static {
System.out.println("执行Grandpa的静态快");
}
public Grandpa(){
System.out.println("执行Parent的构造方法");
}
static{
System.out.println("执行Grandpa的静态快222222");
}
{
System.out.println("执行Grandpa的普通快222222");
}
}

Parent类

 package com.xinye.test;

 public class Parent extends Grandpa{
protected int a = 111;
{
System.out.println("执行Parent的普通块");
}
static {
System.out.println("执行Parent的静态快");
}
public Parent(){
System.out.println("执行Parent的构造方法");
}
public Parent(int a){
this.a = a ;
System.out.println("执行Parent的构造方法:InitParent(int a)");
}
static{
System.out.println("执行Parent的静态快222222");
}
{
System.out.println("执行Parent的普通快222222");
}
}

Child类

 package com.xinye.test;

 public class Child extends Parent {
{
System.out.println("执行Child的普通块");
}
static {
System.out.println("执行Child的静态快");
}
public Child(){
super(222);
System.out.println("a = " + a);
System.out.println("执行Child的构造方法");
}
static{
System.out.println("执行Child的静态快222222");
}
{
System.out.println("执行Child的普通快222222");
}
}

测试类

 package com.xinye.test;

 public class Test {

     public static void main(String[] args) {
/**
*
* 第一步:
* Grandpa如果有静态块,按照Grandpa的静态块声明顺序依次执行
* Parent中如果有静态块,按照Parent中的静态块声明顺序依次执行
* Child中如果有静态块,按照Child中的静态块声明顺序依次执行
* 第二部:
* 如果Grandpa中有普通块,按照Grandpa的普通块声明顺序依次执行
* 执行完毕后,执行被调用的构造方法(如果Parent调用了Grandpa中的特定构造;如果没有则调用默认构造)
* 如果Parent中有普通块,按照Parent的普通块的声明顺序依次执行
* 执行完毕后,执行被调用的构造方法(如果Child调用了Parent的特定构造;如果没有则调用默认构造)
* 如果Child中有普通块,按照Child的普通块的声明顺序依次执行
* 执行完毕后,执行被客户端调用的特定构造方法
*/ new Child();
}
}

执行结果

 执行Grandpa的静态快
执行Grandpa的静态快222222
执行Parent的静态快
执行Parent的静态快222222
执行Child的静态快
执行Child的静态快222222
执行Grandpa的普通块
执行Grandpa的普通快222222
执行Parent的构造方法
执行Parent的普通块
执行Parent的普通快222222
执行Parent的构造方法:InitParent(int a)
执行Child的普通块
执行Child的普通快222222
a = 222
执行Child的构造方法
上一篇:Oracle----date


下一篇:react native调试