A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 亓华森 中级黑马   /  2014-4-1 16:25  /  954 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Test1 {
  2.         public static int k=0;
  3.         public static Test1 t1=new Test1("t1");
  4.         public static Test1 t2=new Test1("t2");
  5.         public static int i=print("i");
  6.         public static int n=99;
  7.        
  8.         public int j=print("j");
  9.        
  10.         {
  11.                 print("构造块");
  12.         }
  13.        
  14.         static{
  15.                 print("静态块");
  16.         }
  17.        
  18.         public Test1(String str){
  19.                 System.out.println((++k)+":"+str+"    i="+i+"    n="+n);
  20.                 ++i;++n;
  21.         }
  22.        
  23.         public static int print(String str){
  24.                 System.out.println((++k)+":"+str+"    i="+i+"    n="+n);
  25.                 ++n;
  26.                 return ++i;
  27.         }
  28.        
  29.         public static void main(String...strings ){
  30.                
  31.         }
  32. }

  33. 输出结果:
  34. 1:j    i=0    n=0
  35. 2:构造块    i=1    n=1
  36. 3:t1    i=2    n=2
  37. 4:j    i=3    n=3
  38. 5:构造块    i=4    n=4
  39. 6:t2    i=5    n=5
  40. 7:i    i=6    n=6
  41. 8:静态块    i=7    n=99
复制代码

问题:i和n到底是什么时候声明的,public static Test1 t1=new Test1("t1");这句会去执行构造块和构造方法,但是这时候public static int i=print("i");并没执行,i是哪里出来的?它是按顺序先声明所有变量然后才从头再挨个赋值吗?
一道经典问题,大神们现身吧~

评分

参与人数 1技术分 +1 收起 理由
朱神必 + 1

查看全部评分

2 个回复

倒序浏览
静态优先存在于内存中,
在这里 public static int print(String str) 方法是静态的,
当你使用   new Test1("t1");  时候,构造函数会运行,但静态方法已经完成初始化了,
所以这里构造方法里可以使用静态的变量及方法。
回复 使用道具 举报
类一加载到内存,首先静态代码块先加载 然后是构造代码块。最后才是对象的构造函数
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马