阿里巴巴2014校园招聘研发笔试JAVA附加题一

转自:http://blog.sina.com.cn/s/blog_4e1763890101qns6.html

题目:

[java]  view plain copy
  1. package com.test.excise;  
  2. public class Test {  
  3. public static int k=0;  
  4. public static Test t1=new Test("t1");  
  5. public static Test t2=new Test("t2");  
  6. public static int i=print("i");  
  7. public static int n=99;  
  8. private int a=0;  
  9. public int j=print("j");  
  10. {  
  11. print("构造块");  
  12. }  
  13. static   
  14. {  
  15. print("静态块");  
  16. }  
  17.  public Test(String str)  
  18.  {  
  19. System.out.println((++k)+":"+str+"   i="+i+"    n="+n);  
  20.     ++i;++n;  
  21.  }  
  22.  public static int print(String str)  
  23.  {  
  24. System.out.println((++k)+":"+str+"   i="+i+"    n="+n);  
  25.     ++n;  
  26.      return++i;  
  27.  }  
  28.  public static void main(String args[])  
  29.  {  
  30. Test t=new Test("init");  
  31.  }  
  32. }  


求输出?
[java]  view plain copy
  1. 输出结果:  
  2. 1:j    i=0    n=0  
  3. 2:构造块    i=1    n=1  
  4. 3:t1    i=2    n=2  
  5. 4:j    i=3    n=3  
  6. 5:构造块    i=4    n=4  
  7. 6:t2    i=5    n=5  
  8. 7:i    i=6    n=6  
  9. 8:静态块    i=7    n=99  
  10. 9:j    i=8    n=100  
  11. 10:构造块    i=9    n=101  
  12. 11:init    i=10    n=102  


解析:
1.若没有main函数中的代码,结果1-8仍可输出,因为这是在程序编译时就执行的
2.对于类中的各代码的执行顺序:静态变量在类编译时全部初始化,非静态变量仅在实例化时才初始化
   所以先初始化t1,newTest1()时会将类中非静态变量初始化,所以初始化j,非静态代码块,然后调用构造函数,t2亦是如此,最后类编译完后,进入main函数,执行t,t初始化前先将Test中非静态变量初始化,然后调用构造函数
3.对于经继承关系的类的执行顺序:父类静态代码块和变量->子类静态代码块和变量->父类非静态代码块->父类构造函数->->子类非静态代码块->子类构造函数


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值