- public class People
- {
- public static int num=0;//静态变量
- String name;
- static//静态初始化块
- {
- System.out.println(num+”:静态初始化块”);
- }
- {//实例初始化块
- System.out.println(num+”:实例初始化块”);
- }
- public People(String name)
- {
- System.out.println(num+”:构造函数初始化”);
- this.name=name;
- num++;
- }
- /*
- @param args
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- People people=new People(“lip”);
- People people2=new People(“xiaoli”);
- }
- }
public class People
{
public static int num=0;//静态变量
String name;
static//静态初始化块
{
System.out.println(num+”:静态初始化块”);
}
{//实例初始化块
System.out.println(num+”:实例初始化块”);
}
public People(String name)
{
System.out.println(num+”:构造函数初始化”);
this.name=name;
num++;
}
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
People people=new People(“lip”);
People people2=new People(“xiaoli”);
}
}
运行效果:
new两个实例,从运行结果可以看出,静态变量和静态初始化块都是在类加载到系统时,加载到系统中,静态初始化块只运行一次,实例初始化块和构造函数都是运行两次,也就是说,有一个对象就执行一次实例初始化块和构造函数。 三个的执行顺序也显而易见:静态初始化块 -实例初始化块- 构造函数
在eclipse中打开编译的People.class如下图所示:
0 iconst_0 这个是将静态变量加载到内存中
20 ldc <String “:静态初始化块”> [32] 执行静态初始化块,只加载一次到内存
来源:blog.csdn.net/yilip/article/details/41986953