Java初始化顺序总结 - 静态变量、静态代码块、成..
时间:2010-08-11 来源:neuguotd
3,装载父类A后,完成静态动作(包括静态代码和变量,它们的级别是相同的,安装代码中出现的顺序初始化)
4,装载子类B后,完成静态动作
类装载完成,开始进行实例化
1,在实例化子类B时,先要实例化父类A
2,实例化父类A时,先成员实例化(非静态代码)
3,父类A的构造方法
4,子类B的成员实例化(非静态代码)
5,子类B的构造方法
先初始化父类的静态代码--->初始化子类的静态代码-->初始化父类的非静态代码--->初始化父类构造函数--->初始化子类非静态代码--->初始化子类构造函数
测试代码:
abstract class base
{
public int age=getNumber(100);
static{
System.out.println("base static block");
}
{
System.out.println("base nonstatic block");
}
static int sage=getNumber(50);
base(){
System.out.println(age);
System.out.println("base start");
draw();//会调用子类覆盖后的方法,这儿是0!
System.out.println("base end");
}
static int getNumber(int base){
System.out.println("base.getNumber int"+base);
return base;
}
public void draw(){
System.out.println("base.draw");
}
}
public class initializeOrder extends base{
public int age=getNumber(1001);
private int _radius=getNumber(10);
static int sage=getNumber(250);
static{
System.out.println("subclass static block");
}
{
System.out.println("subclass nonstatic block");
}
initializeOrder(int radius){
_radius=radius;
System.out.println(age);
draw();//这儿是1000
System.out.println("initializeOrder initialized");
}
public void draw(){
System.out.println("initializeOrder.draw "+_radius);
}
public static void main(String[] args) { // TODO Auto-generated method stub
new initializeOrder(1000);
}
}
输出为:
base static block
base.getNumber int50
base.getNumber int250
subclass static block
base.getNumber int100
base nonstatic block
100
base start
initializeOrder.draw 0
base end
base.getNumber int1001
base.getNumber int10
subclass nonstatic block
1001
initializeOrder.draw 1000
initializeOrder initialized