Static code block, construction code block, construction method, static code Construction Method
Run the following code and observe the result:
Package com. test; public class HelloB extends HelloA {public HelloB () {}{ System. out. println ("I'm B class");} static {System. out. println ("static B");} public static void main (String [] args) {new HelloB () ;}} class HelloA {public HelloA () {}{ System. out. println ("I'm A class");} static {System. out. println ("static ");}}
The result is as follows:
Static Astatic BI'm A classi' m B class
Resolution:
1. Static code block: it is initiated in step 3 of the class loading process. The main purpose is to grant the class variable an initial value.
2. Construct a code block: it is independent and must be attached to a carrier for running. Java puts the constructed code block in front of each constructor to instantiate some common instance variables and reduce the amount of code.
3. constructor: Used to instantiate a variable.
Summary:
1 is a class level, and 2 and 3 are instance-level. Therefore, 1 must take precedence over 2 and 3.
The execution sequence is 1> 2> 3;