Java parent-child class loading order

Table first conclusion, the order of loading is as follows:

Superclass Static Member Variables > Superclass Static Code Block > Subclass Static Member Variables > Subclass Static Code Block > Superclass Non-static Member Variables > Superclass Non-static Code Block > Superclass Constructor > Subclass Non-Static Member Variables > Subclass Non-Static Code Block > Subclass Constructor

How can I remember this long? !

Here to help you summarize a few characteristics:

  1. Member variables > code block > constructor (constructor).
  2. Static (shared) > Non-static (private).
  3. Subclass static > parent non-static (private).

1. Static > Non-static

  1. This is triggered if and only if the class is first called by new (the first time it is called by the classloader) in the program (regardless of permanent generation recycling), but not if you just call main. class.
  2. This is another example of classes being loaded before objects.

2. Member variables > Member methods > Constructor

  1. To load the entire class, you need to know which member variables the class has and initialize those attributes.private String A = "";orprivate String A;After that, the object of this class is countedThe complete.
  2. Initializing a non-static member variable is part of the preparation of a new object, equivalent to a constructor that does not accept any external arguments to the class. The same goes for non-static code blocks. Therefore, member variables > non-static code blocks > constructors.

3. Subclass static > parent non-static

  1. Combined with the first rule, it is also relatively easy to get this rule.

The test code is as follows:

/ * * *@author Ander.Li
 */
public class Main {

	static class A {
		static Hi hi = new Hi("A");

		Hi hi2 = new Hi("A2");

                // Static code block
		static {
			System.out.println("A static");
		}

                // Non-static code block
		{
			System.out.println("A non static");
		}

		public A(a) {
			System.out.println("A init"); }}// B is A subclass of A
	static class B extends A {
		static Hi hi = new Hi("B");

		Hi hi2 = new Hi("B2");

                // Static code block
		static {
			System.out.println("B static");
		}

                // Non-static code block
		{
			System.out.println("B non static");
		}

		public B(a) {
			System.out.println("B init"); }}static class Hi {
		public Hi(String str) {
			System.out.println("Hi "+ str); }}public static void main(String[] args) {
		System.out.println("[First] new B:");
		B b = new B();
		System.out.println();
		System.out.println("[Second] new B:");
		b = newB(); }}Copy the code

The running results are as follows:

[First] new B: Hi A A static Hi B B static Hi A2 A non static A init Hi B2 B non static B init [Second] new B:  Hi A2 A non static A init Hi B2 B non static B initCopy the code