First, take a look at a piece of code to test everyone. Please output the following code results without running the program:
class Insect {int i = 9;int j;Insect() {prt("i = " + i + ", j = " + j);j = 39;}static int x1 = prt("static Insect.x1 initialized");static int prt(String s) {System.out.println(s);return 47;}}public class Test extends Insect {int k = prt("Beetle.k initialized");Test() {prt("k = " + k);prt("j = " + j);}static int x2 = prt("static Beetle.x2 initialized");static int prt(String s) {System.out.println(s);return 63;}public static void main(String[] args) {prt("Beetle constructor");Test b = new Test();}}
Code result:
static Insect.x1 initializedstatic Beetle.x2 initializedBeetle constructori = 9, j = 0Beetle.k initializedk = 63j = 39
If your results are correct, I really admire it ......
When running Java on Test, the first thing that happens is to load the program and find the class outside. During the loading process, the loader should pay attention to it
There is a basic class (that is, the meaning of the extends keyword), so it is loaded. Whether or not you want to generate one of the basic classes
This process will occur (please try to mark the object creation code as a comment and confirm it by yourself ).
If the base class contains another base class, the other base class is loaded immediately, and so on. Next, in the root base class (this is
Insect) executes static initialization, and then runs in the next category class, and so on. It is critical to ensure this order, because the sequence class
The initialization of may depend on the correct initialization of the basic class members.
In this case, all necessary classes have been loaded, so you can create objects. First, all basic data types in this object are set to them.
And the object handle is set to null. Then, the basic class builder is called. In this case, the call is automatically performed. However
You can use super to specify the builder call from the line (just like the first operation in the Test () builder ). Basic Class Construction
The processing process is exactly the same as that of the pipeline class builder. After the basic builder is complete, the instance variables are initialized in the original order. Most
Then, execute the remaining body parts of the builder.