previously understood initialization rules for Java instance variables to pick up the flowers--see the initialization of Java instance variables inside
Today we continue to sort out the initialization sequence and details of class variables, and the friends you need can review them together.
The initialization of a class variable is similar to the initialization of an instance variable, and the initialization of the constructor is less the case than the instance variable. There are generally only two cases when defining class variables when initializing and initializing in static blocks.
Rule: In both cases, all class variables are declared and the memory is requested, and the assignment operation is initialized in all the static blocks, in the same order as the source code.
First understand the following code
static double number = 100;
The fact that the JVM handles the above statement is equivalent to
static double number;static{number = 100;}
Follow the above rules and give a complete example
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 Stubsy Stem.out.println ("number =" + number); System.out.println ("Count =" + count);}}
according to the rules, first the number and count of the double type are declared and the memory (memory request does not explain), and execute the equivalent code block and the original code block, the above code 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, figure
Static block assignment in both cases (the second source code on the left and the first source code on the right)
In this case, the initialization of class variables is roughly as above.
Pick up the flowers--and look at the initialization of Java class variables inside