java learning (1) static code block construction code block construction method execution sequence and attention issues

Today I summed up the execution order of the static code block construction code block construction method in java and its attention.

First of all, you need to know that static code blocks are loaded with class loading, while construction code blocks and construction methods are loaded with object creation.

At that time, I made such a small case (presumably most of the Java students have done this, I don't know if they understand it)

copy code
class Fu{
    static {
        System.out.println("Fu static code");
    }
    {
        System.out.println("Fu code");
    }
    public Fu(){
        System.out.println("Fu GouZao");
    }
}

class Zi extends Fu{
    static {
        System.out.println("Zi static code");
    }
    {
        System.out.println("Zi code");
    }
    public Day () {
        System.out.println("Zi GouZao");
    }
}

public class Text{
    public static void main(String[] args) {
        Zi zi = new Zi ();
    }
}
copy code

1. When compiling Text.java, the Fu class is loaded first, so the static code block of the Fu class is executed first, and then the Zi class is loaded, and the static code block of the Zi class is executed, which is nothing to say

2. Then create the Zi object. Everyone knows that the construction code block takes precedence over the construction method . At this time, the problem comes. At this time, you should first look at the construction method of the Zi class . There is an implicit super in the construction method of the Zi class. () is executed first, so the constructor of the Fu class is found, and the constructor of the Fu class also has an implicit super() execution (calling the constructor of the Object class), and there is no return result. Before executing the method body of the Fu class constructor, first execute the Fu class constructor code block (Fu code), then execute the Fu class constructor method body (that is, Fu GouZao), and finally return to the Zi class constructor, At this time, the super() of the Zi class has been executed. Before executing the method body of the Zi class constructor, the Zi class constructor code block (Zi code) is executed, and then the Zi class constructor method body (Zi GouZao) is executed.

The final result is:

Fu static code
Zi static code
Fu code
Fu GouZao
Zi code
Zi GouZao

I don't know if you are confused, I will summarize here: static is related to the class, it must be loaded first, and before the execution of the construction code block, it is necessary to check whether there is this() or super() in the construction method, and some The words are executed after it, and finally the method body of the constructor is executed

(If there is any misunderstanding, please give pointers and discuss together)

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325572047&siteId=291194637
Recommended