Java中类的初始化过程

话不多说,先上段代码~~

public class IniTest {
	public sample s = new sample("s");
	static{
		System.out.println("This is the static block");
	}
	public static sample s1 = new sample("s1");
	public IniTest(){
		System.out.println("This is IniTest constructor");
	}
	
	static{
		System.out.println("This is the second static block");
		sample s3 = new sample("s3");
	}
	
	public static void main(String[] args){
		IniTest t1 = new IniTest();
		IniTest t2 = new IniTest();
	}
}


class sample{
	
	public sample(String s){
		System.out.println("This is sample constructor and the object is " + s);
	}
}
上述代码的输出是什么?为什么是这样的输出呢?这里涉及到Java中类的初始化过程。下面我们一起来学习类的加载及初始化过程。

1、类的加载过程

Java启动之后,首先会加载相关的类。类的“加载过程”分为加载、验证、准备、解析、初始化5个阶段。在“加载过程”中,虚拟机会定位到字节码的二进制流,生成Class对象,进行验证,分配类变量(static修饰的),进行引用的解析,并生成<clinit>方法。跟我们相关的便是这个<clinit>方法。

  • <clinit>方法是编译器自动收集类中的所有类变量的赋值语句和static{}块合并产生的,顺序由语句的顺序决定。
  • <clinit>方法与构造函数不同,不需要显式调用父类的<clinit>方法,这点会由虚拟机保证。


2、类的初始化过

  • 类的初始化过程由构造函数及实例变量确定,
  • 如果类中有实例变量,则会首先初始化实例变量(个人认为这是为了保证在构造函数中不会“向前引用”,即变量仍未分配内存空间,便对变量进行操作),实例变量的初始化顺序由代码确定。
  • 执行构造函数进行初始化
3、对上述代码的分析:
首先是          IniTest t1 = new IniTest();     此语句会导致虚拟机加载IniTest类,正确定位到IniTest类后,执行<clinit>方法,此时<clinit>方法中的内容为:
	static{
		System.out.println("This is the static block");
	}
	public static sample s1 = new sample("s1");
	
	static{
		System.out.println("This is the second static block");
		sample s3 = new sample("s3");
	}
因此首先会看到下面的输出
This is the static block
This is sample constructor and the object is s1
This is the second static block
This is sample constructor and the object is s3
之后执行类的初始化过程。
  1. 初始化实例变量s
  2. 执行构造函数
最后的结果相信已经非常明了了。下面是所有的输出。
This is the static block
This is sample constructor and the object is s1
This is the second static block
This is sample constructor and the object is s3
This is sample constructor and the object is s
This is IniTest constructor

4、最后的说明
由于类的加载过程只会执行一次,所以<clinit>方法也只会执行一次,所以如果吧main方法改为
	public static void main(String[] args){
		IniTest t1 = new IniTest();
		IniTest t2 = new IniTest();
	}

程序的输出为
This is the static block
This is sample constructor and the object is s1
This is the second static block
This is sample constructor and the object is s3
This is sample constructor and the object is s
This is IniTest constructor
This is sample constructor and the object is s
This is IniTest constructor

即执行顺序为<clinit>    ------------->      <init>     ----------------->    <init>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值