BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #33897同步于 2014/8/20
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

问一道java题

melot
2014/8/20镜像同步14 回复
public class Test1 { public static int k = 0; public static Test1 t1 = new Test1("t1"); public static Test1 t2 = new Test1("t2"); public static int i = print("i"); public static int n = 99; public int j = print("j"); { print("构造块"); } static { print("静态块"); } public Test1(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[] strings) { Test1 t = new Test1("init"); } } 先说一下我个人的看法,我觉得,在程序一开始的时候应该先执行static{print("静态块")}, 随后在new Test1("t1")的时候,先执行{print("构造块")},然后再是 Test1(String str)里的输出,Test1("t2")应该重复Test1("t1")的步骤,其余按步骤走 所以我做这道题的时候得到的结果是: 1:静态块 i=0 n=0 2:构造块 i=1 n=1 3:t1 i=2 n=2 4:构造块 i=3 n=3 5:t2 i=4 n=4 6:i i=5 n=5 7:j i=6 n=99 8:构造块 i=7 n=100 9:init i=8 n=101 但是,程序跑出来的时候,发现错的好离谱,下面是正确的结果 对于这个结果,表示本人太渣了,很多东西看不懂,所以单步执行,查看了一下。不过对于一些问题不是很明白,想请教一下: 1.在执行到 public static Test1 t1 = new Test("t1")的时候,按下一步,跑到 public Test1(String str) { 这一行上,再下一步时,就跳到 public int j = print("j")这一行上去了,这是为什么? 2.static { print("静态块“)}为什么是在public static int i = print("i")之后执行,还是说它每次都恰好在main()函数之前执行? 求好心人解答,谢谢
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
wangxiaobupt机器人#1 · 2014/8/20
你先把 public static Test1 t1 = new Test1("t1"); public static Test1 t2 = new Test1("t2"); 这两句注释掉 然后看能不能看懂顺序 看懂之后再加上上面其中一句再看看
HB0318机器人#2 · 2014/8/20
对于静态变量、静态初始化块、变量、初始化块、构造器,它们的初始化顺序依次是(静态变量、静态初始化块)>(变量、初始化块)>构造器。
melot机器人#3 · 2014/8/20
嗯,看懂了,谢谢 【 在 wangxiaobupt 的大作中提到: 】 : 你先把 : public static Test1 t1 = new Test1("t1"); : public static Test1 t2 = new Test1("t2"); : ...................
melot机器人#4 · 2014/8/20
soga,终于了解了,谢谢 【 在 HB0318 的大作中提到: 】 : 对于静态变量、静态初始化块、变量、初始化块、构造器,它们的初始化顺序依次是(静态变量、静态初始化块)>(变量、初始化块)>构造器。
mumubin机器人#5 · 2014/8/20
阿里笔试题 【 在 melot 的大作中提到: 】 public class Test1 { p...
melot机器人#6 · 2014/8/20
嗯 【 在 mumubin 的大作中提到: 】 : 阿里笔试题 : public class Test1 { : p...
noEasy机器人#7 · 2014/8/20
1:构造块 i=0 n=0 2:t1 i=1 n=1 3:构造块 i=2 n=2 4:t2 i=3 n=3 5:i i=4 n=4 6:j i=5 n=99 7:静态块 i=6 n=100 8:构造块 i=7 n=101 9:init i=8 n=102 我跑出来的詹怎么是这样
superzhaoyy机器人#8 · 2014/8/20
http://m.blog.csdn.net/blog/perfe_ct/6563051可以参考一下这个
melot机器人#9 · 2014/8/20
你是不是代码的顺序改变了 【 在 noEasy 的大作中提到: 】 : 1:构造块 i=0 n=0 : 2:t1 i=1 n=1 : 3:构造块 i=2 n=2 : ...................