In Java, Static code block, construction code block, ordinary code block, constructor order is a basic Java learners must master, this blog is to let you can clear up the order between them.

Classification of code blocks

There are three types of code blocks: Static code blocks, construction code blocks, and common code blocks

Code block execution order Static code block — > Construct code block — > constructor — > plain code block

The code block execution order in inheritance: superclass static block > subclass static block > superclass code block > superclass constructor > subclass code block > subclass constructor

1. Static code block (also known as static block, static initialization block)

The code in a Java static code block runs when the class loads the JVM and is executed only once, meaning that the code can be invoked without instantiating the class. In general, static code blocks are used when some code must be executed at project startup, so static blocks are often used to initialize class attributes!

Static Blocks of code

2. Static blocks are often used to perform initialization of class attributes. 3. Static blocks take precedence over various code blocks and constructors. Static code blocks can be defined anywhere in a class except in the method body. Static code blocks cannot access ordinary variables

As described in section 4, a static code block cannot exist in any method body. In fact, it is very simple because ordinary methods can run the method by loading the class and then new the instantiation object, while static code blocks can run only after loading the class. In the case of static methods, when the class is loaded, the static method is also loaded, but we must access it by the class name or object name, which means that static code blocks are actively run by themselves, whereas static methods are run by passive calls. Either way, we need to make it clear that the presence of a static code block runs automatically when the class is loaded, and that it does not run automatically in either normal or static methods.

The static code block described in 5 cannot access ordinary variables for the same simple reason. Ordinary variables are called by instance objects. There are no instance objects in static code blocks. Why call variables?

Static Static code blocks use formats

static{... }Copy the code

2. Construct code blocks (also called construct initializer blocks)

The name is inseparable from the construction method! Yes, but still and constructor has essential difference, as we all know, each method can have a lot of construction method, each to create an object is the constructor to perform a, and a construction method can create N object, a constructor is “cold”, and construct a code block is “lick the dog”, as long as the class instance for an object, The construct code is executed once, taking advantage of the fact that the construct code block is called once in advance each time the object is created, so it can count the number of times the object is created. Of course, relatively few code blocks are constructed!

Construct code block summary:

The constructor code block is called once each time the object is created. The constructor code block takes precedence over the constructor. The constructor code block is defined in the class

The “dependency” in 2 can be understood to mean that if the object is not instantiated (that is, the constructor is not executed), the construction code block will not be executed!

3. Code block (also known as normal code block, initialization block)

Code block summary

3. The only obvious difference between a normal code block and a constructed code block is that a constructed code block is defined in a class, while a normal code block is defined in a method body

Perform sequential code tests

That’s it, let’s start coding!

package com.gx.initializationblock;

public class Initializationblock {

    int intA;
    int intB;


    public Initializationblock() {
        System.out.println("No-parameter constructor 00000000");
    }

    public Initializationblock(int a) {
        System.out.println("One-parameter constructor");
        
    }


    {
        intA = 10;
        intB = 15;

        System.out.println("Construct initialization block 11111");
    }

    {
        System.out.println("Structure initialization block 22222");
    }

    {
    	
        System.out.println("Construct initialization block 33333");
    }

    // Statically initialize the block
    static {
        System.out.println("Static initialization block 01010101");
    }

    static {
        System.out.println("Static initialization block 0202020202");
    }
    public void method(){
    	{
    		System.out.println("Common initialization block"); }}}Copy the code

Test the demo

package com.gx.initializationblock;

Since static blocks are done during the initialization phase of a class, * so when a second object of a class is created, the class's static blocks are not executed * * In a single class, statically initializing blocks, initializing blocks, The constructor * initialized multiple class inheritance, static initialization blocks, constructor execution order In succession, successively to the execution of the parent class A static block parent class B static block, finally subclass static block, and then execute the parent class non-static block and A constructor, then the B class non-static blocks and constructor, and finally execute A subclass of static block and constructor * /
public class Demo1 {
    public static void main(String[] args) {
        Initializationblock initializationblock = new Initializationblock();
        initializationblock.method();
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- --");
        Static code blocks are executed only once!!
        Initializationblock initializationblock2 = new Initializationblock(); // Because static blocks are completed during the initialization phase of a class, when the second object of a class is created, the static blocks of that class are not executed
        initializationblock2.method();
        Initializationblock initializationblock3 = newInitializationblock(); initializationblock3.method(); }}Copy the code

Print the result

Statically initializing blocks01010101Statically initializing blocks0202020202Construct the initialization block11111Construct the initialization block22222Construct the initialization block33333No parameter constructor00000000Common initialization block ------------ Constructs the initialization block11111Construct the initialization block22222Construct the initialization block33333No parameter constructor00000000A normal initialization block constructs an initialization block11111Construct the initialization block22222Construct the initialization block33333No parameter constructor00000000Plain initialization blockCopy the code

Conclusion: Execute sequential static code block > construct code block > Constructor > plain code block

Inherits the execution order of each code block in

BaseThree — > BaseTwo — > BaseOne BaseOne

package com.gx.initializationblock;

public class BaseOne {

    public BaseOne() {
        System.out.println("BaseOne Constructor");
    }

    {
        System.out.println("BaseOne initialization Block");
        System.out.println();
    }

    static {
        System.out.println("BaseOne Static Initialization Block"); }}Copy the code

BaseTwo class

package com.gx.initializationblock;

public class BaseTwo extends BaseOne {
    public BaseTwo() {
        System.out.println("BaseTwo constructor");
    }

    {
        System.out.println("BaseTwo initialization block");
    }

    static {
        System.out.println("BaseTwo Static Initialization block"); }}Copy the code

BaseThree class

package com.gx.initializationblock;

public class BaseThree extends BaseTwo {
    public BaseThree() {
        System.out.println("BaseThree constructor");
    }

    {
        System.out.println("BaseThree initialization block");
    }

    static {
        System.out.println("BaseThree Static Initialization block"); }}Copy the code

Test demo2 class

package com.gx.initializationblock;

/ * note: In inheritance, the static block of parent class A is executed first, the static block of parent class B is executed, and the static block of parent class B is subclassed finally, and then the non-static block and constructor of parent class A are executed. This is followed by class B's non-static blocks and constructors, and finally the subclass's non-static blocks and constructors */
public class Demo2 {
    public static void main(String[] args) {
        BaseThree baseThree = new BaseThree();
        System.out.println("-- -- -- -- --");
        BaseThree baseThree2 = newBaseThree(); }}Copy the code

The results

BaseOne static initialization block BaseTwo Static initialization block BaseThree Static initialization block BaseOne initialization block BaseTwo initializer block BaseThree Initializer block BaseThree constructor ----- BaseOne initialization block BaseOne constructor BaseTwo initialization block BaseTwo constructor BaseThree Initialization block BaseThree constructorCopy the code

Initialization block multiple class inheritance, static initialization blocks, the constructor of execution order is: has the implementation of the parent class A static block, the parent class B static block, finally subclass static block, and then execute the parent class non-static block and A constructor, then the B class non-static blocks and constructor, finally perform subclasses of static block and the constructor (note: Where ABC corresponds to BaseOne, BaseTwo, BaseThree 】

Conclusion: In the inheritance of multiple classes, the execution order of initializer block, static initializer block and constructor is: parent static block > subclass static block > parent code block > parent constructor > subclass code block > subclass constructor

QnQ Finally, bloggers are not great and can make mistakes! Welcome to correct if there is something wrong! Thank you so much!