Code block static code block initializes the execution order of the constructor in-place

Problem Description:

Java instantiates a class. If this class has not only a constructor, but also a code block, a static code block, and an instance of another class that is initialized in place, what is the order of execution of the code?


Samples and running results

people class

package Extends;

import Dog.Dog;

class people {
    
    
    public int age=100;
    public String name;

    Dog dog=new Dog();

    public people() {
    
    
        System.out.println("people");
    }
    {
    
    
        System.out.println("people的代码块");
    }
    static {
    
    
        System.out.println("people中的静态代码块");
    }
}

dog class

public class Dog {
    
    
    String name;
    int age;
    public Dog(){
    
    
        name="大黄";
        age=3;
        System.out.println("dog的初始化");
    }
}

Main function

public class Main {
    
    
    public static void main(String[] args) {
    
    
        people p1=new people();
        System.out.println("---------");
        people p2=new people();
    }
}

Insert picture description here

Cause Analysis:

Here, in the people class, there are not only code blocks, static code blocks, and construction methods, but also initialize a dog instance on the spot. From the results, we can see that the execution of the static code block is always the earliest, but once executed, the next level is : In-place initialization and code blocks. Whoever writes the two will execute the first, and the last one is the construction method.


import Dog.Dog;

class people {
    
    
    public int age=100;
    public String name;
    public people() {
    
    
        System.out.println("people");
    }
    {
    
    
        System.out.println("people的代码块");
    }
    static {
    
    
        System.out.println("people中的静态代码块");
    }
    Dog dog=new Dog();
}

Insert picture description here
At this time, the construction of dog is after the code block.

Guess you like

Origin blog.csdn.net/weixin_45070922/article/details/112991240