Loading order
First serve conclusion:
Parent static properties (member variables)> parent class static block of code> subclass Static Property> subclass static block of code> parent non-static properties> parent class non-static block of code> parent class constructor> subclass non-static properties> subclasses block non-static> subclass constructor
So how long you remember it? !
Here to help you summary the following characteristics:
- Static properties and code block, if and only if the new class is the first time in the program or to trigger the first class is (without regard to generation of permanent recovery) loading the call. Precisely because of these reasons, the class takes precedence over the objects are loaded / new, that is static in preference to non-static.
- Attributes (member variables) take precedence over construction method, can be understood, this whole class is loaded, you need to know which classes have properties, and those properties after initialization is complete, the object of this class is considered complete. In addition, one non-static code block is actually a preparation of new objects, be a constructor does not accept any external parameters. Therefore, the attribute> non-static block> constructor.
- Interestingly, the static part of the (first four) is the parent class> subclass, rather than static part (after 6) is the parent class> subclass.
- Also easy to overlook that the non-static block of code in each new object will be run, it can be understood: non-static code block is ready to work (non-static block of code> constructor) before the official constructor.
1 /** 2 * @author Lean.Li 3 * @date 2018/10/15 4 */ 5 public class Main { 6 7 static class A { 8 static Hi hi = new Hi("A"); 9 10 Hi hi2 = new Hi("A2"); 11 12 static { 13 System.out.println("A static"); 14 } 15 16 { 17 System.out.println("AAA"); 18 } 19 20 public A() { 21 System.out.println("A init"); 22 } 23 } 24 25 26 static class B extends A { 27 static Hi hi = new Hi("B"); 28 29 Hi hi2 = new Hi("B2"); 30 31 static { 32 System.out.println("B static"); 33 } 34 35 { 36 System.out.println("BBB"); 37 } 38 39 public B() { 40 System.out.println("B init"); 41 } 42 } 43 44 static class Hi { 45 public Hi(String str) { 46 System.out.println("Hi " + str); 47 } 48 } 49 50 public static void main(String[] args) { 51 is System.out.println ( "B initial new new:" ); 52 is B = B new new B (); 53 is System.out.println (); 54 is System.out.println ( "B Second new new:" ); 55 B = new new B (); 56 is } 57 is 58 }
Results are as follows:
初次 new B: Hi A A static Hi B B static Hi A2 AAA A init Hi B2 BBB B init 第二次 new B: Hi A2 AAA A init Hi B2 BBB B init