黑马程序员技术交流社区

标题: 分析一道面试题的运行过程 [打印本页]

作者: 段郎    时间: 2014-4-27 21:59
标题: 分析一道面试题的运行过程
求着段代码的运行过程
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[] args) {
            Test1 t=new Test1("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


作者: 轻语。    时间: 2014-4-27 23:33
本帖最后由 伍叶竹 于 2014-4-27 23:34 编辑

好复杂的题,捣鼓了好久一点想法:装载Test1.class,静态变量在类编译时全部初始化,非静态变量仅在实例化时才初始化
.执行:public static  Test1 t1=new Test1("t1");  在调用构造函数之前对实例成员初始化,
即先public int j=print("j");调用到print 打印:  1:j   i=0  n=0
然后执行实例代码块,即print("构造块"),
最后调用构造函数Test1("t1");分别打印:2:构造块   i=1  n=1                 
                                                                      3:t1      i=2  n=2
打印结果的4-6行是 Test1 t2=new Test1("t2");执行的结果。 同上。
然后是: public static int i=print("i");   打印:7:i   i=6  n=6
然后是静态块:static{     print("静态块");    }        打印:8:静态块   i=7  n=99

最后9-11是主函数中的语句了  和1、2、3行打印一个道理。不过要注意此时n的值。
断网前最后的挣扎。 我只能帮你到这儿了。{:3_64:}








作者: ς高眼光の目标    时间: 2014-4-28 02:52
看晕了 不过肯定是静态代码快,然后构造代码块,再到构造函数,的
作者: 段郎    时间: 2014-4-28 10:11
伍叶竹 发表于 2014-4-27 23:33
好复杂的题,捣鼓了好久一点想法:装载Test1.class,静态变量在类编译时全部初始化,非静态变量仅在实例化 ...

谢谢啊,我再好好悟悟
作者: ﹊佑雨时杰↘    时间: 2014-4-28 23:25
  好乱啊   不过打上断电 很清晰的哦




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2