This article describes a static block of code for a class, constructs a code block, and constructs a method execution flow problem. First look at an example
/*** Created by Lili on 15/10/19.*/classperson{Static{System.out.println ("Execute person Static code block"); } {System.out.println ("Execute person construct code block"); } PublicPerson () {System.out.println ("Execute person Constructor method"); }}classStudentextendsperson{Static{System.out.println ("Execute student static code block"); } {System.out.println ("Executing student construction code block"); } PublicStudent () {System.out.println ("Execute student Construction Method"); }} Public classextendsstaticconstruct { Public Static voidMain (String args[]) {Student Student=NewStudent (); }}
The results of the implementation are as follows:
0
The sequence of execution of the description program is:
Static code block--"Construction code block---" construction method
Execution Process Explanation:
New is the student class, but student is the child person class, so when loading the student class, the person class is loaded first, and the static content is loaded with the load of the class, so the "execute person Static code block" is printed first, Executes a static block of code after the student.
After loading the class, start the main method, execute the student constructor method, that is, initialize the student, but the student is inherited from person, must first initialize the person, so first call the person class's NULL parameter construction method to initialize, However, the construction code block of the person class takes precedence over the construction method execution, so the construction code block of the person class executes first, and is executed after the method is constructed. The construction code block and construction method of the student class are then executed.
The execution order here is not related to the construction of a default parent class in the subclass construct Super (), not to the hidden super () to begin initializing the parent class , the initialization of the class is hierarchical initialization, which initializes the parent class, initializes the subclass, initializes the process of each class, The initialization of the class, the initialization of the advanced member variables, the initialization order of the member variables is: The default initialization, that is, int is 0 this--"display initialization, for example, int type display initialized value-" constructor method initialization, so this is done here to the construction method.
The execution order of code blocks and construction methods in "Java Foundation" inheritance