Coming soon -- let's look at the initialization inside story of java variables, inside story of java
I have previously understood the initialization rules of java instance variables.
Today, we will continue to clarify the initialization sequence and details of class variables. If you need them, you can review them together.
The initialization of class variables is similar to the initialization of instance variables. Compared with the initialization of instance variables, the initialization of the constructor is much less. Generally, there are two scenarios: initialization when defining class variables and initialization in static blocks.
Rule: in the above two cases, declare all class variables and apply for memory, and initialize all assignment operations in the static block in the same order as the source code.
First, understand the following code
static double number = 100;
In fact, the above statements processed by JVM are equivalent
static double number;static{number = 100;}
A complete example is provided based on the above rules.
public class TestStatic {static double number = 100;static{System.out.println("number = "+ number);count = 200;}static double count = 300;/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("number = "+ number);System.out.println("count = "+ count);}}
According to the rules, first declare the double type number and count and apply for memory (memory application is not described), and execute the equivalent code block and the original code block. The above code is equivalent to the following code
public class TestStatic {//static double number = 100;static double number;static double count;static{number = 100;}static{System.out.println("number = "+ number);count = 200;}//static double count = 300;static{count = 300;}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("number = "+ number);System.out.println("count = "+ count);}}
Use the javap tool to view the compiler source code.
Static block assignment in two cases (the left side is the second source code and the right side is the first source code)
At this point, the initialization of class variables is roughly as above.