The order of data initialization in a class is one of the questions that the interviewer likes very much, this article uses an example to introduce the Java sub-class, the parent class static code block, the field, the non-static code block, the field and the constructor execution order and the number of times.
First, the package structure
Cat Inheritance Animal
The runner contains the main function, the program entry
The Sing class is used primarily to print the sequence number of the execution
Second, the Code
Public classAnimal {Sing S1=NewSing (1, "Animal\tnot static field"); StaticSing s2=NewSing (2, "animal\tstatic field"); StaticSing S3; Sing S4; Sing S5; Static{S3=NewSing (3, "Animal\tstatic code area"); } {S4=NewSing (4, "Animal\tnot Static code area"); } Animal () {S5=NewSing (5, "Animal\tconstructor"); } }
Public classCatextendsAnimal {Sing S1=NewSing (1, "Cat\t\tnot static field"); StaticSing s2=NewSing (2, "cat\t\tstatic field"); StaticSing S3; Sing S4; Sing S5; Static{S3=NewSing (3, "Cat\t\tstatic code area"); } {S4=NewSing (4, "Cat\t\tnot Static code area"); } Cat () {S5=NewSing (5, "Cat\t\tconstructor"); }}
Public class Sing { Sing (int mark,string flag) { System.out.println (Mark+ "+flag);} }
Public class Runner { publicstaticvoid main (string[] args) { System.out.println ("+++++++++++++++++++++first+++++++++++++++++++++++++++++"); New Cat (); System.out.println ("+++++++++++++++++++++second++++++++++++++++++++++++++++"); New Cat (); }}
III. Results of implementation
+++++++++++++++++++++first+++++++++++++++++++++++++++++
2 animal static field
3 animal static Code Area
2 cat static field
3 cat & nbsp; static Code Area
1 animal not static field
4 animal Not static code area
5 animal constructor
1 cat not static Field
4 cat not static code area
5 cat Constructor
+++++++++++++++++++++second++++++++++++++++++++++++++++
1 animal not static Field
4 animal not static code area
5 animal constructor
1 cat not static field
4 cat not static code area
5 cat constructor
Iv. Summary
Initialization order: Parent static field-"Parent static code block-" Subclass static field-"subclass static code block-" Parent non-static field-"Parent non-static code block-" Parent construction-"Subclass non-static field-" Subclass non-static code block-"sub-class construction
Follow these guidelines:
1, static > Non-static
2. Parent Class > Subclass
3. Fields > Code blocks > Constructors
4, static field, static code block in the program life cycle only initialized once
Java subclasses, static code blocks in the parent class, fields, non-static code blocks, fields, and initialization order and number of constructors