Java child and parent class loading order

Java child and parent class loading order

program

/** 
 * @ClassName: B 
 * @Description: 父类,测试java继承时,构造器、静态代码块、非静态代码块的执行顺序。
 */
public class B {
    
    
    public B(){
    
    
        System.out.println("this is B's constructor!");
    }

    static{
    
    
        System.out.println("this is B's static block!");
    }

    {
    
    
        System.out.println("this is B' static not block!");
    }

}
/** 
 * @ClassName: A 
 * @Description: 子类,测试java继承时,构造器、静态代码块、非静态代码块的执行顺序。
 */
public class A extends B{
    
    
    /** 
     * @Title:A
     * @Description:构造器  
     */
    public A(){
    
    
        System.out.println("this is A's constructor!");
    }

    static{
    
    
        System.out.println("this is A's static block!");
    }

    {
    
    
        System.out.println("this is A' static not block!");
    }

}
/** 
 * @ClassName: Main 
 * @Description: 测试类,测试java继承时,构造器、静态代码块、非静态代码块的执行顺序。<br>
 * 结论:this is B's static block!<br>
         this is A's static block!<br>
         this is B' static not block!<br>
         this is B's constructor!<br>
         this is A' static not block!<br>
         this is A's constructor!<br>
 */
public class Main {
    
    
    public static void main(String[] args) {
    
    
        A a = new A();
    }
}

result

this is B’s static block!
this is A’s static block!
this is B’ static not block!
this is B’s constructor!
this is A’ static not block!
this is A’s constructor

in conclusion

When constructing an object in Java, first load this class and the parent class of this class into memory . During the loading process , the static code blocks in the class will be executed . The order of execution is:Parent class static code block, subclass static code block

Then you can continue to execute the program (you must have this class in memory to construct the entity object of this class).

Before constructing the entity class of this class, you need to call the non-static code block in the class first, and then execute the constructor of the class to create an entity class. The order of execution is:Parent class non-static code block, parent class constructor, sub class non-static code block, sub class constructor

The reason for this sequence is: when new A();executed, the constructor of class A will be called, but if class A has a parent class, the constructor of the parent class will be called first, and because the parent class has non-static code blocks, it will be executed first The non-static code block of the parent class is executed, and then the constructor of the parent class is executed, and then class A is turned. Similarly, the non-static code block of class A is executed first, and then the constructor is executed.

Guess you like

Origin blog.csdn.net/qq_32727095/article/details/113863852