If you can’t learn the Java initialization process, you will hit me.

 

public class Example {
    // 静态变量
    public static int staticVar = 1;
    // 实例变量
    public int instanceVar = 2;

    // 静态初始化块
    static {
        System.out.println("执行静态初始化块");
        staticVar = 3;
    }

    // 实例初始化块
    {
        System.out.println("执行实例初始化块");
        instanceVar = 4;
    }

    // 构造方法
    public Example() {
        System.out.println("执行构造方法");
    }

    public static void main(String[] args) {
        System.out.println("执行main方法");

        Example e1 = new Example();
        Example e2 = new Example();

        System.out.println("e1的静态变量:" + e1.staticVar);
        System.out.println("e1的实例变量:" + e1.instanceVar);
        System.out.println("e2的静态变量:" + e2.staticVar);
        System.out.println("e2的实例变量:" + e2.instanceVar);
    }
}

 Results of the

执行静态初始化块
执行main方法
执行实例初始化块
执行构造方法
执行实例初始化块
执行构造方法
e1的静态变量:3
e1的实例变量:4
e2的静态变量:3
e2的实例变量:4

 As can be seen from the output results, the static initialization block is executed when the class is loaded, will only be executed once, and takes precedence over the execution of the instance initialization block and constructor methods; the instance initialization block is executed every time an object is created, and is executed before the constructor method.

 First add the static variable a =1 to the parent class Sup, then execute the code block b = 3, and then b =2 (in fact, whichever static variable or static code block is executed first ), then execute the static variable a = 11 of the subclass , b =22, and then load the Test test class new 

 Sub a =6, b =9 Then load it into the subclass, execute super(a,b) to the parent class, print a and b 1, 2 in the parent class, execute this.a, accept 6,9, and print a, b That is 6, 9. After execution, return to the subclass to execute printing. At this time, a=11, b=22 

At this time, all subclasses and parent classes are loaded. Return to the test class and execute sub to print a, b 11, 22 and execute sup to print 6 and 9.

 First, go to the parent class to load the static variable a = 1, the static code block b = 3, then execute the static variable b = 2, and then go to the test class new Sub a = 6, b = 9. This will go to sub and load the structure a of Sbu. =6, b =9, execute the next statement super (a, b)

Print, a, b are 0, 0 because this will int a =11, b =22 in Sub, and then print the loaded a =1, b =2.

After executing to this.a = a, a =6, b =7 will be passed to this. The execution print has not been loaded yet, so the a, b of sub are still 0, 0.

super.a and b this will be 6, 9.

This will perform the loading of int a = 11, b = 22, and then perform the printing in the Sub construction, which will super a = 6 b = 9, this of a = 11, b = 22. 

Homework questions

11
0
11
0
11
32

Guess you like

Origin blog.csdn.net/pachupingminku/article/details/132560063