1, if there is a parent class, first initialize the parent class, and then initialize the subclass
2. Initialize static member variables, static code blocks (code enclosed by static {}), and initialize non-static member variables, non-static code blocks (code surrounded by curly braces). Static member variables, non-static member variables are initialized in a defined order.
3. Call constructor
Class Bowl {Bowl (int marker) {System.out.println ("Bowl (" + marker + ")"); } void f (int marker) {System.out.println ("f (" + marker + ")"); }}class Cupboard {Bowl B3 = new Bowl (3); static Bowl b4 = new Bowl (4); Cupboard () {System.out.println ("cupboard ()"); B4.F (2); } void F3 (int marker) {System.out.println ("F3 (" + Marker + ")"); } static Bowl B5 = new Bowl (5);} Class Table {static Bowl B1 = new Bowl (1); Table () {System.out.println ("table ()"); B2.F (1); } void F2 (int marker) {System.out.println ("F2 (" + marker + ")"); } static Bowl b2 = new Bowl (2);} public class Test {public static void main (string[] args) throws Interruptedexception {System.out.println ("Cre ating new Cupboard () in main "); New Cupboard (); System.out.println ("Creating New Cupboard () in main"); New Cupboard (); T2.F2 (1); T3.F3 (1); } static Table t2 = new Table (); static cupboard T3 = new cupboard ();}
1. Start running, the JVM loads the test class first, then initializes the static member variable T2, T3
2. Then load the table class and initialize the class static member variable B1, B2, call the bowl constructor to generate the object
3. Call the table constructor to generate the T2 object
4. Load the Cupboard class, initialize the static member variable B4, B5, and then b3 the non-static member variable and call the bowl constructor
5. Call the cupboard constructor to generate the T3 object
6. Run Main function
7. Run new cupboard, at which time cupboard is loaded into memory, static member variables are no longer initialized, but non-static member variables are still initialized again
Operation Result:
Bowl (1) Bowl (2) Table () f (1) Bowl (4) Bowl (5) Bowl (3) cupboard () F (2) Creating new Cupboard () in Mainbowl (3) cupboard () F (2) Creating New Cupboard () in Mainbowl (3) cupboard () F (2) F2 (1) F3 (1)
Java programming thought notes-initialization order of classes