试题
考点

java语言-面向对象编程-构造函数&初始化

面5笔5

请写出以下代码执行输出:

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;
private int a = 0;
public int j = print("j");
{
print("构造块");
}
static {
print("静态块");
}

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

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

public static void main(String args[]) {
Test t = new Test("init");
}

}


前往“校招VIP”小程序,刷题更快
最新校招难题刷题,快来进刷题群吧
解答

题目看着很混乱,但是按着代码看下去,道理也很简单,输出为:

1:j   i=0    n=0
2:构造块 i=1 n=1
3:t1 i=2 n=2
4:j i=3 n=3
5:构造块 i=4 n=4
6:t2 i=5 n=5
7:i i=6 n=6
8:静态块 i=7 n=99
9:j i=8 n=100
10:构造块 i=9 n=101
11:init i=10 n=102


原则:

代码中与输出有关的代码有几种,静态变量、静态块、普通变量、构造函数。

在构造函数前执行的有

1. 静态变量和静态块,按代码顺序执行,且只执行一次

2. 普通变量和代码块,按代码顺序执行,类的每次调用都需要初始化


之后才是构造函数的调用。

答案也就很清楚了








评论

星夜

2021-09-11 08:30:00

0 0

加载更多