------ class loading mechanism on the active and passive references cited

Class load

Load -> Authentication -> Prepare -> parse -> Initialization -> Use -> Uninstall

Active reference to the class (the class initialization will occur)

An object 1.new
2. static member class is called (except final constants) and static methods
3. java.lang.reflect package reflecting the class method calls
4. When starting a virtual machine, java Hello, the initialization will Hell type, start type where the main method
5. when initializing a class, if the parent class is not initialized, it will initialize its parent

Passive reference to the class (class initialization does not happen)

1. When accessing a static class, the only true statement of the static class field will be initialized
2. defined by reference to an array class, the class does not trigger initialization
3. The constant references to such does not trigger initialization

Test code is as follows:





public class Demo01 {
	static{
		System.out.println("静态初始化Demo01");
	}
	
	
	public static void main(String[] args) throws Exception {
		System.out.println("Demo01的main方法!");
		
		
		//主动引用
//		new C();//new一个对象
//		System.out.println(C.width);//调用类的静态成员
//		Class.forName("com.bjsxt.test.C");//使用java.lang.reflect包的方法对类进行反射调用
		
		
		//被动引用
//		System.out.println(C.MAX);//引用常量不会触发此类的初始化
//		C[] as = new C[10];//通过数组定义类的引用,不会触发该类的初始化
		System.out.println(B.width);//当访问一个静态类时,只有真正声明该静态类的域才会被初始化(此处因为width在
									//C中初始化,所以B不会初始化,C初始化)
										
		
	}
}

class B  extends C {
	static {
		System.out.println("静态初始化B");
	}
}

class C extends C_Father {
	public static int width=100;   //静态变量,静态域    field
	public static final  int MAX=100; 
	
	static {
		System.out.println("静态初始化类C");
		width=300;
	}
	public C(){
		System.out.println("创建C类的对象");
	}
}

class C_Father extends Object {
	static {
		System.out.println("静态初始化C_Father");
	}
}

The results are as follows:

Static initialization Demo01
main method of Demo01!
Static initialization C_Father
static initialization class C
300

Published 24 original articles · won praise 0 · Views 602

Guess you like

Origin blog.csdn.net/weixin_43896829/article/details/104535337