天天看點

靜态代碼塊、非靜待代碼塊、靜态變量的執行次序

關于靜态代碼塊、非靜待代碼塊、靜态變量的執行次序,大的問題相信大家都明白,但是最近有同學問到了如下問題,覺得難以了解其輸出。其問題的代碼如下:

public class StaticTest {

    public static void main(String[] args) {

        staticFunction();

    }

    static StaticTest st = new StaticTest();

    static {

        System.out.println("1");

    }

    {

        System.out.println("2");

    public StaticTest() {

        System.out.println("3");

        System.out.println("a=" + a + " b=" + b);

    private static void staticFunction() {

        System.out.println("4");

    int a = 100;

    static int b = 112;

}

其輸出為:

2

3

a=100 b=0

1

4

其實,任何問題碰到了,我們的首要任務是分解,就像上面這段代碼,我們首先把這行代碼注釋掉:

//static StaticTest st = new StaticTest();

繼而繼續執行,輸出為:

這個很好了解,如果類被用到,靜态代碼塊會首先被執行,是以一般來說,靜态代碼塊被用作與類變量(靜态變量)的初始化。

接下來,我們先不分析上面的代碼,先看一段其它的代碼:

public class StaticTest {

    static Test01 test01 = new Test01();

}

class Test01{

    static int b = 112;

    public Test01(){

        System.out.println( "b=" + b);

輸出為多少,你一定會說,是:

b=112

完美,我們的了解沒錯,但是,仿佛最上面的代碼就不對了,我們還原下最上面的代碼:

    public StaticTest(){

    static StaticTest test01 = new StaticTest();

輸出為:

b=0

我覺得如果這個時候我們還不能了解的話,我們稍稍改變下代碼的位置:

static int b = 112;

static StaticTest test01 = new StaticTest();

輸出結果為112;

是以把最開始的那段代碼中b的定義移到st的上面一行,

static StaticTest st = new StaticTest();

輸出就變為:

a=100 b=112

因為b和st都是靜态變量,它們之間還有個先來後到的次序。

剩下的,應該都是很好了解的了。

靜态代碼塊、非靜待代碼塊、靜态變量的執行次序

本文基于

Creative Commons Attribution 2.5 China Mainland License

釋出,歡迎轉載,演繹或用于商業目的,但是必須保留本文的署名

http://www.cnblogs.com/luminji

(包含連結)。如您有任何疑問或者授權方面的協商,請給我留言。

繼續閱讀