今天所要详细讲解的是Java中的初始化,也就是new对象的过程中,其程序的行走流程。

先说没有静态成员变量和静态代码块的情况。

 public class NormalInit {

     public static void main(String[] args) {
System.out.println("Inside main()");
new Mugs();
System.out.println("new Mugs() completed");
new Mugs(1);
System.out.println("new Mugs(1) completed");
}
}
class Mugs {
Mug mug1=new Mug(1); {
System.out.println("mg1 & mg2 initialized");
} public Mugs() {
System.out.println("Mugs");
} public Mugs(int i) {
System.out.println("Mugs(int)");
}
Mug mug2=new Mug(2);
}
class Mug{
public Mug(int market) {
System.out.println("Mug("+market+")");
}
void f(int market) {
System.out.println("f("+market+")");
}
}

上述代码的运行结果为:

Inside main()
Mug(1)
mg1 & mg2 initialized
Mug(2)
Mugs
new Mugs() completed
Mug(1)
mg1 & mg2 initialized
Mug(2)
Mugs(int)
new Mugs(1) completed

代码很能说明问题,new对象后,顺次执行构造方法之外的成员变量初始化或者非静态代码块,再去执行构造函数。

下面,是带有静态成员变量和静态代码的情况。

 public class StaticInit {

     public static void main(String[] args) {
System.out.println("Creating new CupBoard() in main");
new Cupboard();
} static Cupboard cupboard = new Cupboard();
} class Bowl {
public Bowl(int market) {
System.out.println("Bowl(" + market + ")");
}
} class Cupboard {
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
static {
new Bowl(6);
}
{
new Bowl(7);
} public Cupboard() {
System.out.println("CupBoard");
} static Bowl bowl5 = new Bowl(5);
}

运行结果为:

Bowl(4)
Bowl(6)
Bowl(5)
Bowl(3)
Bowl(7)
CupBoard
Creating new CupBoard() in main
Bowl(3)
Bowl(7)
CupBoard

可以看出,new对象之后,先顺次执行静态成员变量的初始化和静态代码块中的程序,再顺次执行实例成员变量的初始化及代码块,最后执行构造方法。

 当然,静态的所有内容都只执行一次!!

05-11 22:00