usage Scenario : In a Java program, when an object is instantiated, all member variables of the object's class are initialized first, only after all class members have completed initialization.
Object is created by invoking the constructor of the class where the object resides .
the principle of initialization :
(1) Static objects take precedence over non-static object initialization, and static objects can be initialized only once, but non-static objects may be initialized multiple times.
(2) The superclass takes precedence over the derived class initialization.
(3) initialization is performed in the order in which the member variables are defined, even if the variable definitions are scattered among the method definitions, and they are initialized before any methods (including constructors) are called.
Packagetest;/*Order of Java program initialization: Superclass static variable superclass static code block subclass static variable Quantum class static code block * Superclass non-static variable superclass non-static code block superclass constructor subclass non-static code block subclass non-static code block * Subclass Constructor*/classBase {Static{System.out.println ("Parent class static Block");//(1)} {System.out.println ("Parent class block");//(3) } PublicBase () {System.out.println ("Parent class construction method");//(4) } Public Static voidA () {intA//Static methods cannot have static constants, because the static method shares a chunk of memory, mainly for accumulation, and if the constant of static constants cannot be added, it will conflict.System.out.println ("Normal static method of the parent class"); } } Public classDerivedextendsBase {Static intA=1; Static intb=2; Static{System.out.println ("Subclass static Block");//(2)} {System.out.println ("Subclass Block");//(5) } PublicDerived () {System.out.println ("Sub-class constructor");//(6) } Public Static voidMain (string[] args) {base.a (); NewDerived (); }}/**public static void Main (string[] args) {new Derived (); Base.a (); } parent class static block subclass static Block Parent class Block parent class constructor method subclass block subclass constructor Parent class Normal static method*//**public static void Main (string[] args) {base.a (); New Derived (); } parent class static block subclass static Block parent class Normal static method parent class block Parent class constructor method subclass Block Subclass Constructor **/
Java Program Initialization Order