Four blocks of code in Java
Building code Blocks
Normal code block (non-static code block)
Static code block
Synchronizing code blocks
Their order of execution:
Analysis: When the new Child () is executed, it first goes to see if there is a static block of code inside the parent class, and if so, it first executes the contents of the static code block inside the parent class, and then executes the static block of code inside the subclass (own class) after the contents of the static code block inside the parent class are executed. When the static code block of a subclass executes, it goes on to see if the parent class has no non-static block of code, and if there is a non-static block of code that executes the parent class, the non-static code block of the parent class is executed, and the parent class's constructor is executed, and then it goes to see if the subclass has non-static A non-static block of code that executes subclasses if there is one. The non-static code block of the subclass executes and then executes the subclass's constructor, which is the initialization order of an object.
Summary: Object initialization order: first executes the parent class static content, after the parent class static content executes, then executes the subclass the static content, when the subclass static content executes, then goes to see the parent class has the non-static code block, if has executes the parent class non-static code block, the parent class's non-static code block executes completes , then executes the parent class's construction method, and after the parent class's construction method executes, it goes on to see if the subclass has no non-static code block, and if there is one, executes the subclass's non-static code block. The non-static code block of the subclass executes and then executes the subclass's construction method. In short, the static code block content executes first, then executes the parent class non-static code block and construction method, then executes the subclass non-static code block and constructs the method.
Note: The constructor of a subclass, regardless of the constructor with no arguments, will first look for the parent class's constructor without parameters.
If the parent class does not have a constructor with no arguments, the subclass must use the supper key to call the parent class with the constructor of the parameter, otherwise the compilation cannot pass.
Four blocks of code in Java