Open source are the greatest wealth---WANGPENG
posts - 46, comments - 11, trackbacks - 0, articles - 0
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

[转载]Java中的初始化块

Posted on 2009-06-29 18:19 WANGPENG 阅读(389) 评论(0)  编辑  收藏 所属分类: Java

在Java中,有两种初始化块:静态初始化块和非静态初始化块.

静态初始化块:使用static定义,当类装载到系统时执行一次.若在静态初始化块中想初始化变量,那仅能初始化类变量,即static修饰的数据成员.
非静态初始化块:在每个对象生成时都会被执行一次,可以初始化类的实例变量.

非静态初始化块会在构造函数执行时,且在构造函数主体代码执行之前被运行.


 1 package com.tiandinet.studyjava;
 2 
 
 3 public class
 TestInitiateBlock {
 4 
 
 5 
    {
 6         System.out.println("In non-static initialization block!"
);
 7 
    };
 8 
 
 9     static
 {
10         System.out.println("In static initialization block!"
);
11 
    };
12 
 
13     public
 TestInitiateBlock() {
14         System.out.println("In Constructor1!"
);
15 
    }
16 
 
17     public void
 show() {
18         System.out.println("In show()!"
);
19 
    }
20 
 
21     /**

22      * @param args
23      */

24     public static void main(String[] args) {
25         TestInitiateBlock ti = new
 TestInitiateBlock();
26 
        ti.show();
27 
    }
28 
 
29 }

运行结果:
In static initialization block!
In non-static initialization block!
In Constructor1!
In show()!

只有注册用户登录后才能发表评论。


网站导航: