- public class Test5 {
- private static int a;
- private int b;
- static{
- Test5.a=3;
- System.out.println(a);
- Test5 t=new Test5();
- t.f();
- t.b=1000;
- System.out.println(t.b);
- }
- static{
- Test5.a=4;
- System.out.println(a);
- }
- public static void main(String[] args) {
- }
- static{
- Test5.a=5;
- System.out.println(a);
- }
- public void f(){
- System.out.println("hhahhahah");
- }
- }
運行結果:
3
hhahhahah
1000
4
5
分析:
static 代碼塊也叫靜態代碼塊,是在類中獨立於類成員的static語句塊,可以有多個,位置可以隨便放,它不在任何的方法體內,JVM加載類時會執行這些靜態的 代碼塊,如果static代碼塊有多個,JVM將按照它們在類中出現的先後順序依次執行它們,每個代碼塊只會被執行一次 ( 我記得藍色之路里就有這麼一道類似的變態題目)
-------------------------------------------------------------
http://yahaitt.iteye.com/blog/143457
靜態代碼塊的執行順序
補充:
在有類內非靜態代碼塊的情況下,執行順序應該如下:
靜態代碼塊的執行順序:
1.父類的靜態代碼塊
2.子類的靜態代碼塊
3.父類的非靜態代碼塊
4.父類的構造函數
5.子類的非靜態代碼塊
6.子類的構造函數
================================================
- //靜態代碼塊的執行順序
- import static java.lang.System.out;
- class Bird
- {
- public Bird()
- {
- out.print("b2 ");
- }
- {out.print("b1 ");}
- static
- {
- out.print("bs0 ");
- }
- }
- class Raptor extends Bird
- {
- static
- {
- out.print("rs1 ");
- }
- public Raptor()
- {
- out.print("r2 ");
- }
- {
- out.print("r3 ");
- }
- static
- {
- out.print("rs4 ");
- }
- }
- public class G015 extends Raptor{
- public static void main(String[] args) {
- out.print("pre ");
- new G015();
- out.println("G015 ");
- }
- }
輸出結果應爲:
bs0 rs1 rs4 pre b1 b2 r3 r2 G015