1. 程式人生 > >阿里java面試題分析

阿里java面試題分析

這道題來源於阿里巴巴的面試

public class Text {                               //  1

    public static int k = 0;                           //2

    public static Text t1 = new Text("t1");            //3

    public static Text t2 = new Text("t2");            //4

    public static int i = print("i");                  //5

    public static int n = 99;                          //6

    public int j = print("j");                         //7

    {

        print("構造塊");                                //8

    }

    static {

        print("靜態塊");                             // 9

    }

 

    public Text(String str) {                         //10

        System.out.println((++k) + ":" + str + "   i=" + i + "    n=" + n);

        ++i;

        ++n;

    }

 

    public static int print(String str) {            //11

        System.out.println((++k) + ":" + str + "   i=" + i + "    n=" + n);

        ++n;

        return ++i;

    }

 

    public static void main(String args[]) {         //12

        Text t = new Text("init");

    }

}

 

此程式首先執行public static int k = 0;隨後進行載入類Text,先初始化靜態屬性(new Text("t1")),執行   7和8         然後執行 3,之後又遇到new Text("t2");然後又進行初始化靜態屬性,執行 7和8,初始化完成之後,開始執行4,之後便執行5,6,9;然後去執行  Text t = new Text("init"),執行之前先例項化類,然後在去執行相應的建構函式。

 

注意;如有不對請聯絡博主