阿里笔试题之写出程序输出结果:
package com.patrick.bishi;
public class TestVar {
public static int k = 0;
public static TestVar t1 = new TestVar("t1");
public static TestVar t2 = new TestVar("t2");
public static int i = print("i");
public static int n = 99;
public int j = print("j");
{
print("构造");
}
static {
print("静态");
}
public TestVar(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) {
TestVar t = new TestVar("init");
}
}
结果:
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
分析:
初始化一个类(main方法执行之前),主要是对静态成员变量的初始化,过程分为两步:1)按照静态成员变量的定义顺序在类内部声明成员变量;2)按类中成员变量的初始化顺序初始化。
本例中,先声明成员变量k,t1,t2,i,n,此时,k=i=n=0;t1=t2=null,然后按顺序初始化这几个成员变量,k复制0,t1初始化,执行构造函数,构造函数执行需要先对对象的成员属性先进行初始化,因此执行 j 的初始化,再执行对象的代码块,再是构造函数本身,同理t2初始化,接下来再是 i 和 n 的初始化,然后到main方法中的对象 t 的初始化,对象的初始化同理t1的初始化。
参考http://www.cnblogs.com/lmtoo/archive/2012/04/08/2437918.html,得到此例转换成class的类似代码:
package com.patrick.bishi;
public class TestVarClass {
public static int k = 0;
public static TestVarClass t1 = null;
public static TestVarClass t2 = null;
public static int i = 0;
public static int n = 0;
static {
k = 0;
t1 = new TestVarClass("t1");
t2 = new TestVarClass("t2");
i = print("i");
n = 99;
print("静态");
}
int j = 0;
public TestVarClass(String str) {
j = 0;
{
j = print("j");
print("构造");
}
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) {
TestVarClass t = new TestVarClass("init");
}
}