您的位置:首页 > 编程语言 > Java开发

Java的执行顺序,笔试遇到的问答题(做完这题执行顺序不会再错)

2013-09-24 00:01 232 查看
public class Test {
public static int k = 0;
public static Test t1 = new Test("t1");
public static Test t2 = new Test("t2");
public static int i= print("i");
public static int n = 99;

{
print("构造块");
}

static{
print("静态块");
}

public Test(String str) {
System.err.println(++k + ":" + str + "  i=" + i + "  n=" + n);
++n;
}

public static int print(String str) {
System.err.println(++k + ":" + str + "  i=" + i + "  n=" + n);
++n;
return ++i;
}

public static void main(String[] args) {
Test test = new Test("init");
System.out.println("=========================================");
Test test1 = new Test("init1");

}

}

经过查看课本和Debug追踪:

1.当第一次创建类时,会给这个类的成员变量中静态变量 给予初始值(int为0,boolean为false)

2. 根据代码 给静态变量赋值

3. 静态块

4.初始化成员变量中的非静态变量

5. 构造块

第二次创建时:

由上述的 4. 开始执行。

特殊情况:

        静态变量中 又是创建这个类??

答:经过debug追踪,发现这个类时直接上述的 4. 开始执行。

debug模式下结果:(注意如果直接执行 :是优化过的,结果就不同)

1:   j  i=0  n=0

2:   构造块  i=1  n=1

3:   t1  i=2  n=2

4:   j  i=2  n=3

5:   构造块  i=3  n=4

6:   t2  i=4  n=5

7:   i  i=4  n=6

8:   静态块  i=5  n=99

9:   j  i=6  n=100

10:   构造块  i=7  n=101

11:   init  i=8  n=102

=========================================

12:   j  i=8  n=103

13:   构造块  i=9  n=104

14:   init1  i=10  n=105

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: