About Java static block

Categories: Java; Tagged with: ; @ May 15th, 2012 0:06
package scjp.liguoliang.com;

/**
 * I'm try to see the static block run rules,
 * B extends A, A has a static a, when we use B.a, class B did not loaed, just Class A loaded.
 * If B also has a static a, A and B will be loaded.
 * If a is finle, A and B will not be loaded both.
 * @author Li Guoliang
 *
 */
public class TestClassLoading {
	public static void main(String[] args) {
		System.out.println(B.a);
		System.out.println(C.c);
	}
}

class A {
	static String a = "A.a"; // how about if this is final
	static {
		System.out.println("Static_A_Class");
	}
	
	{
		System.out.println("Instance_A");
	}
}

class B extends A{
	// static String a = "B.a";
	static {
		System.out.println("Static_B_Class");
	}
}

/**
 * This class is designed for test the squence of static variable and block. 
 * They run by the sequence of the code.
 * @author Li Guoliang
 *
 */
class C {
	
	static {
		System.out.println("Static_C");
	}
	static C c = new C();
	
	public C() {
		System.out.println("Constructor_C");
	}
}

Output

Static_A_Class
A.a
Static_C
Constructor_C
scjp.liguoliang.com.C@161f10f

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.