Static code blocks, properties and methods will be loaded when the class is loaded, and their loading order is in sequence; when a class is instantiated, it will first load common properties > building blocks > constructors > ordinary methods
Static block: declared with static, executed when the JVM loads the class, only once
Construction block: The class is defined directly with {}, which is executed every time an object is created, and it takes precedence over the execution of the constructor (the initialization content common to different objects is defined in the construction code block, and all objects are uniformly initialized; and the constructor is Initialize the corresponding object)
Static blocks are executed in the order of declaration, so first execute public static B t1 = newB(); this statement creates an object, then the construction block is called again, and the construction block is output
Execution order priority: static block>main()>construction block>constructor method>normal method
public class B { public static B t1 = new B(); public static B t2 = new B(); { System.out.println("Building Block"); } static { System.out.println("static block"); } public static void main(String[] args) { B t = new B(); } }
Finally, the main method executes, creates the object, and outputs the building block
The correct result is: building block building block static block building block
class Demo { int x; static int y = 3; // static code block static { System.out.println("Static code block"); } // define the construction code block { System.out.println("I am constructing a code block"); System.out.println("x=" + x); } //Constructor public Demo() { } static void print() { System.out.println("y=" + y); } void show() { System.out.println("x=" + x + " y=" + y); } } class StaticDemo { public static void main(String[] args) { //The class name calls the print method Demo.print(); //create object Demo d = new Demo(); //assign the member variable x d.x = 10; //call the show method with the object d.show(); } }
Static code block
y=3
I am constructing code block
x=0
x=10 y=3