Java中的初始化详细解析

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

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

 1 public class NormalInit {
 2 
 3     public static void main(String[] args) {
 4         System.out.println("Inside main()");
 5         new Mugs();
 6         System.out.println("new Mugs() completed");
 7         new Mugs(1);
 8         System.out.println("new Mugs(1) completed");
 9     }
10 }
11 class Mugs {
12     Mug mug1=new Mug(1);
13     
14     {
15         System.out.println("mg1 & mg2 initialized");
16     }
17     
18     public Mugs() {
19         System.out.println("Mugs");
20     }
21     
22     public Mugs(int i) {
23         System.out.println("Mugs(int)");
24     }    
25     Mug mug2=new Mug(2);
26 }
27 class Mug{
28     public Mug(int market) {
29         System.out.println("Mug("+market+")");
30     }
31     void f(int market) {
32         System.out.println("f("+market+")");
33     }
34 }

上述代码的运行结果为:

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对象后,顺次执行构造方法之外的成员变量初始化或者非静态代码块,再去执行构造函数。

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

 

 1 public class StaticInit {
 2 
 3     public static void main(String[] args) {
 4         System.out.println("Creating new CupBoard() in main");
 5         new Cupboard();
 6     }
 7 
 8     static Cupboard cupboard = new Cupboard();
 9 }
10 
11 class Bowl {
12     public Bowl(int market) {
13         System.out.println("Bowl(" + market + ")");
14     }
15 }
16 
17 class Cupboard {
18     Bowl bowl3 = new Bowl(3);
19     static Bowl bowl4 = new Bowl(4);
20     static {
21         new Bowl(6);
22     }
23     {
24         new Bowl(7);
25     }
26 
27     public Cupboard() {
28         System.out.println("CupBoard");
29     }
30 
31     static Bowl bowl5 = new Bowl(5);
32 }

 

运行结果为:

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

 

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

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

 

posted @ 2018-03-28 20:36  豪杰杰杰  阅读(731)  评论(0编辑  收藏  举报