In the process of brushing a question, you often encounter problems with the initialization order of classes in Java.
Summarized as follows, easy to review later:
Initialization process:
- First, static member variables and static code blocks in the parent class are initialized in the order in which they appear in the program;
- Then, initialize the static member variables and static code blocks in the subclass, initializing them in the order in which they appear in the program;
- Second, initialize the normal member variables and code blocks of the parent class, and then execute the parent class construction method;
- Finally, the normal member variables and code blocks of the subclass are initialized, and then the construction methods of subclasses are executed.
Examples are as follows:
classC {C () {System.out.print (C); }} classA {c c=NewC (); A () { This("A"); System.out.print (A); } A (String s) {System.out.print (s); }} classTestextendsA {Test () {Super("B"); System.out.print (B); } Public Static voidMain (string[] args) {NewTest (); }}
In the above program, the initialization process of new class test is as follows:
- The constructor method is called to initialize the child object, but because test inherits from Class A, you need to call A's construction method first;
- In test's construction method, the parameter construction method of the parent class is explicitly called by Super("B") , and no parameter construction method is called.
- Before executing A's construction method, it is necessary to initialize its member variables so that the C constructor is executed.
- As a result, the final order of invocation is: Class C's parameterless constructs--Class A's parameter constructs--class test constructs the remainder of the method.
So the result of the final output is:
CBB
The initialization process of Java