java 类加载 对象初始化 静态代码块 非静态代码块

炼心天毅 2016-02-02 05:57:09
求教各路大神,谁能给解释一下这个

public class StaticTest {
public static int k =0 ;
public static StaticTest t1 = new StaticTest("t1") ;
public static StaticTest t2 = new StaticTest("t2") ;
public static int m =3 ;
public static int i = print("i") ; //7:i i=6 n=6 执行完之后i=7 n=7
public static int n =99 ;//重新给n赋值,也就是对n进行初始化,接着执行静态代码块
public int j = print("j") ;//1:j i=0 n=0 4:j i=3 n=3
{
print("构造块 ");//2:构造块 i=1 n=1 5:构造块 i=4 n=4
}
static {
print("静态块");
}
public StaticTest(String str){ //3:t1 i=2 n=2 6:t2 i=5 n=5
System.out.println((++k)+":"+str+" i="+i+" n="+n+" t1="+t1+" t2="+t2+" m="+m) ;
++i;++n ;
}
public static int print(String str){
System.out.println((++k)+":"+str+" i="+i+" n="+n+" t1="+t1+" t2="+t2+" m="+m) ;
++n;
return ++i ;
}
public static void main (String args[]){
/*
new 对象的时候类加载器开始加载类,这个时候只是加载类,并没有执行,也就是并没有进行初始化操作,类加载之后才开始进行初始化操作
这时候k=0 t1=null t2=null i=0 n=0 j=0
初始化的过程是先静态代码块 然后非静态代码块,然后构造函数,其实静态的成员变量和非静态的成员变量在编译的过程中也会加上static{}
对象被创建的时候才进行初始化,创建对象有两种方法
1:显示创建,通过new关键字,调用类的构造函数创建对象
2:隐示创建对象 String = "s";
jvm虚拟机保证静态只执行一次
程序从右向左看,执行,赋值操作是初始化之后的事

*/
StaticTest t = new StaticTest("init") ;

}
}

下面是执行结果
1:j i=0 n=0 t1=null t2=null m=0
2:构造块 i=1 n=1 t1=null t2=null m=0
3:t1 i=2 n=2 t1=null t2=null m=0
4:j i=3 n=3 t1=StaticTest@5ad52411 t2=null m=0
5:构造块 i=4 n=4 t1=StaticTest@5ad52411 t2=null m=0
6:t2 i=5 n=5 t1=StaticTest@5ad52411 t2=null m=0
7:i i=6 n=6 t1=StaticTest@5ad52411 t2=StaticTest@5f3306ad m=3
8:静态块 i=7 n=99 t1=StaticTest@5ad52411 t2=StaticTest@5f3306ad m=3
9:j i=8 n=100 t1=StaticTest@5ad52411 t2=StaticTest@5f3306ad m=3
10:构造块 i=9 n=101 t1=StaticTest@5ad52411 t2=StaticTest@5f3306ad m=3
11:init i=10 n=102 t1=StaticTest@5ad52411 t2=StaticTest@5f3306ad m=3

首先说下我的理解和疑问
1,首先是类加载,同时对各种变量进行初始化,初始化之后结果如下
public static int k =0
public static StaticTest t1 = null
public static StaticTest t2 = null
public static int i =0
public static int n =0
public int j = 0
但是静态代码块里的方法和非静态代码块里的方法不知道怎么处理
2,然后程序继续执行new StaticTest("t1"),但是这个时候为什么没有执行这句话 ????
...全文
124 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

51,407

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧