Home  >  Article  >  Java  >  What is the order in which code blocks and constructors are called during Java object initialization?

What is the order in which code blocks and constructors are called during Java object initialization?

王林
王林forward
2023-05-10 09:52:081082browse

    Priority order of code loading

    Static code blocks, static member variables->Non-static code blocks, non-static member variables->new Other objects call the corresponding object construction method (including the construction method in addition to the local object's methods) -> new local object calls the construction method.

    Note: If the object is new, there are static code blocks and non-static code blocks in the object. Every time the object is new, the non-static code block will be executed once, but the static code block will be executed once. It will only be executed once and then the new object will not be executed again. 】

    Execution order of construction methods

    Parent class static code block (static variable> static block) > Subclass static code block> Parent class construction code block, construction method> ; Construction code blocks and construction methods of subclasses

    Definition of various code blocks

    Static code blocks

    class Demo{ static { //静态代码块...... } }

    Features: 1. Java static code blocks The code will be run when the class is loaded into the JVM and will only be executed once. 2. Static blocks are often used to initialize class attributes and some global initialization work. 3. Static blocks take precedence over various code blocks and constructors. If a class There are multiple static code blocks in it, which will be executed sequentially in the order they are written. 4. Static code blocks can be defined anywhere in the class except in the method body [the method body here is any method body] 5. Static code blocks cannot access ordinary variables.

    Let’s introduce the static code block in detail

    Static code block: A code block declared using the static keyword in java. Static blocks are used to initialize classes and initialize properties of the class. Each static code block is executed only once.

    Since the JVM will execute the static code block when loading the class, the static code block is executed before the main method. If the class contains multiple static code blocks, then the code defined first will be executed first, and the code defined later will be executed. [Note: 1 Static code blocks cannot exist in any method body. 2 Static code blocks cannot directly access static instance variables and instance methods. They need to be accessed through the instance object of the class. 】 Instance code block Instance code block is also called construction initialization block, construction code block, and initialization block.

    class Demo{ { //实例代码块...... } }

    Features:

    • #1. The construction code block is called when creating an object, and will be called once every time an object is created

    • 2. The construction code block takes precedence over the execution of the constructor function. At the same time, the execution of the construction code block depends on the constructor function.

    • 3. The construction code block is executed in Defined in the class

    Partial code block

    Partial code block is also called ordinary code block, method code block

    class Demo{ public void test(){ { //局部代码块...... } } }

    Features : 1. Ordinary code blocks are defined in the method body 2. The format of ordinary code blocks and instance code blocks are the same as {} 3. The only directly visible difference between ordinary code blocks and constructed code blocks is that the constructed code blocks are in the class Defined in, while ordinary code blocks are defined in the method body 4. You can limit the life cycle of variables, release them early, and improve memory utilization

    Verify the execution order of each code block

    The example code is as follows:

    class Init {
        public Init() {
            System.out.println("无参构造器");
        }
        public Init(int a) {
            System.out.println("有参构造器");
        }
        {
            System.out.println("实例代码块1");
        }
        {
            System.out.println("实例代码块2");
        }
        {
            System.out.println("实例代码块3");
        }
        static {
            System.out.println("静态初始化块1");
        }
     
        static {
            System.out.println("静态初始化块2");
        }
    
        public void method(){
        	{
        		System.out.println("普通初始化块");
        	}
        }
    }

    The test code is as follows:

    class Demo {
        public static void main(String[] args) {
            Init init1 = new Init();
            init1.method();
            System.out.println("------------");
            Init init2 = new Init();
            init2.method();
            //多打印几个对象的目的是:方便看出Static静态代码块 是否只执行一次!!!
            System.out.println("------------");
            Init init3 = new Init();
            init3.method();
        }
    }

    The running result is as follows:

    What is the order in which code blocks and constructors are called during Java object initialization?

    ##Conclusion:

    The execution order is: static code block> instance code block> constructor> ordinary code block ,

    and the static code block will be called when the class is loaded, and only called once (executed as the class is loaded).

    So when will the class be loaded?

    - When creating an object instance (new)

    - When creating a subclass object instance, the parent class will also be loaded
    - When using static members of the class (static properties, static methods)

    Verify the execution order of each code block in the inheritance relationship

    The example inheritance relationship is

    Three——> Two——> One,

    The code is as follows:

    class One {
        public One() {
            System.out.println("One构造器");
        }
     
        {
            System.out.println("One实例化块");
        }
     
        static {
            System.out.println("One静态代码块");
     
        }
     
    }
    class Two extends One {
     
        public Two() {
            System.out.println("Two构造器");
        }
     
        {
            System.out.println("Two实例化块");
        }
     
        static {
            System.out.println("Two静态代码块");
        }
     
    }
     
    class Three extends Two {
     
        public Three() {
            System.out.println("Three构造器");
        }
     
        {
            System.out.println("Three实例化块");
        }
        static {
            System.out.println("Three静态代码块");
        }
     
    }
    //测试代码 如下:
    public class Demo {
        public static void main(String[] args) {
            Three three = new Three();
            System.out.println("-----");
            Three three1 = new Three(); //重复执行的目的是为了 验证static是否只执行一次
            System.out.println("-----");
            Two three2 = new Three();   //验证 多态的情况下 用后面的类进行初始化 结果和上面一样
        }
    }

    What is the order in which code blocks and constructors are called during Java object initialization?

    According to the execution results, it can be seen that there are initialization blocks and static initialization blocks in the inheritance of multiple classes , constructor, the actual order of execution is: execute the static block of parent class A, the static block of parent class B, and finally the static block of the subclass, then execute the instance code block and constructor of parent class A, and then class B The instance code block and constructor, and finally execute the instance code block and constructor of subclass C [Note: ABC here corresponds to One, Two, Three]

    Conclusion:

    The execution order of initialization blocks, static initialization blocks, and constructors in the inheritance of multiple classes is:

    父类静态块——>子类静态块——>父类实例代码块——>父类构造器——>子类实例代码块——>子类构造器 ——>(如果有局部代码块, 再正常执行即可, 这里就没必要进行测试了)

    通过字节码深究实例代码块优先于构造器原因

    我们那一段代码作为例子说明下,代码如下:

    class Init {
        public Init() {
            System.out.println("无参构造器");
        }
        public Init(int a) {
            System.out.println("有参构造器");
     
        }
     
        {
            System.out.println("实例代码块1");
        }
     
        {
            System.out.println("实例代码块2");
        }
     
        {
            System.out.println("实例代码块3");
        }
     
        static {
            System.out.println("静态初始化块1");
        }
     
        static {
            System.out.println("静态初始化块2");
        }
     
        public void method(){
            {
                System.out.println("普通初始化块");
            }
        }
    }

    接下来让我们看看 , Init.java编译完的的字节码文件(Init.class)

    What is the order in which code blocks and constructors are called during Java object initialization?

    从这个字节码文件就可以很清晰的看出, 实例代码块实际上是被依次放到了构造方法的第一句, 所以可以的出此结论: 实例代码块的执行顺序是优先于构造器的。

    The above is the detailed content of What is the order in which code blocks and constructors are called during Java object initialization?. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete