java执行顺序

如果父类有静态成员赋值或者静态初始化块,执行静态成员赋值和静态初始化块
如果类有静态成员赋值或者静态初始化块,执行静态成员赋值和静态初始化块
将类的成员赋予初值(原始类型的成员的值为规定值,例如int型为0,float型为0.0f,boolean型为false;对象类型的初始值为null)
如果构造方法中存在this()调用(可以是其它带参数的this()调用)则执行之,执行完毕后进入第7步继续执行,如果没有this调用则进行下一步。(这个有可能存在递归调用其它的构造方法)
执行显式的super()调用(可以是其它带参数的super()调用)或者隐式的super()调用(缺省构造方法),此步骤又进入一个父类的构造过程并一直上推至Object对象的构造。
执行类申明中的成员赋值和初始化块。
执行构造方法中的其它语句。
 
最终的简化顺序版本是:
父类的静态成员赋值和静态块(静态块只执行一次)
子类的静态成员和静态块
父类的构造方法
父类的成员赋值和初始化块
父类的构造方法中的其它语句
子类的成员赋值和初始化块

子类的构造方法中的其它语句


代码实例:


public class Parent
{
  static//加载时执行,只会执行一次
  {
   System.out.println("static block of Parent!");
  }


  public Parent()
  {
   System.out.println("to construct Parent---no!");
 }
 
 public Parent(String name)
 {
   System.out.println("to construct Parent!");
 }
 
 {
   System.out.println("comman block of Parent!");
 }
 }


 class Child extends Parent
 {
 static
 {
   System.out.println("static block of child!");
 }
static//可以包含多个静态块,按照次序依次执行
  {
   System.out.println("second static block of child!");
  }
 
  //普通代码块与变量的初始化等同的,按照次序依次执行
  {
   System.out.println("comman mode of child!");
  }
  private Delegete delegete = new Delegete();
  private Delegete delegete1 = new Delegete("a");
  {
   System.out.println("second comman mode of child!");
  }
 
 //构造顺序,先执行静态块(父类、子类顺序执行)
 //执行父类成员变量的初始化或普通代码块,然后执行构造函数
 //执行子类成员变量的初始化或普通代码块,然后执行构造函数
 public Child()
 {
  super("DLH");
  System.out.println("to construct child!");
 }
 
 public static void main (String[] args) {
  Child c = new Child(); 
  System.out.println("**********************************");
  Child c2 = new Child();
 }
 }


 class Delegete
 {
  static
  {
   System.out.println("static of Delegete!");
  }
  public Delegete()
  {
   System.out.println("to construct delegete!");
  }
  public Delegete(String a)
  {
   System.out.println("to construct delegete ---a!");
  }
 }

运行结果:

static block of Parent!
static block of child!
second static block of child!
comman block of Parent!
to construct Parent!
comman mode of child!
static of Delegete!
to construct delegete!
to construct delegete ---a!
second comman mode of child!
to construct child!
**********************************
comman block of Parent!
to construct Parent!
comman mode of child!
to construct delegete!
to construct delegete ---a!
second comman mode of child!
to construct child!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值