用程序测试了一下实例化一个类的步骤,现总结如下,不对之处请指正。
1、从堆(heap)中为实例变量以及其他数据(如指向其他类的指针以及方法的数据)分配内存;
2、实例变量初始化:
a. 先初始化最高一级父类中的static变量,再按级别由高到低,最后初始化当前类中的static变量;
b. 先初始化最高一级父类中的成员变量(non-static),再调用最高此类的构造方法;
c. 初始化下一级类中的成员变量(non-static),再调用此类的构造方法。如此类推,直到当前类也
完成此操作。
3、创建完毕。
测试代码如下:
//父类:
public class Base {
int a;
{
a = 3;
System.out.println("2. a = "+ a);
}
static int b;
static{
System.out.println("0. b = "+ b);
}
public Base() {
System.out.println("3. BASE");
}
}
//子类
public class Derived extends Base {
public int i;
public String s;
{
i = 100;
s = "fanrey";
System.out.println("4. s = " + s);
}
static int ii;
static String ss;
static{
ii = 10;
ss = "fanrey";
System.out.println("1. ss = " + ss);
}
public Derived() {
System.out.println("5. Derived");
System.out.println("===========================");
System.out.println("s = " + s);
System.out.println("i = " + i);
System.out.println("ss = " + ss);
System.out.println("ii = " + ii);
System.out.println("===========================");
}
public static void main(String[] args){
Derived d = new Derived();
}
}
运行结果:
0. b = 0
1. ss = fanrey
2. a = 3
3. BASE
4. s = fanrey
5. Derived
===========================
s = fanrey
i = 100
ss = fanrey
ii = 10
===========================