Order
1. Static member variables and static code blocks in the parent class
2. Static member variables and static blocks of code in subclasses
3. Common member variables and code blocks in the parent class, constructors for the parent class
4. Generic member variables and code blocks in subclasses, constructors for subclasses
Where the "and" word ends are executed in code order.
Example
Look at the code first:
Father Class
[Java]View PlainCopy
- Public class Father {
- Public String fStr1 = "Father1";
- protected String fStr2 = "Father2";
- private String FSTR3 = "Father3";
- {
- System.out.println ("Father common block be called");
- }
- Static {
- System.out.println ("Father static block be called");
- }
- Public Father () {
- System.out.println ("Father constructor be called");
- }
- }
The first is the Father class, which has a default constructor, a static block of code, and a common code block for easy viewing of the results.
Son class
[Java]View PlainCopy
- Package com.zhenghuiyan.testorder;
- Public class Son extends father{
- Public String SStr1 = "Son1";
- protected String SStr2 = "Son2";
- private String SSTR3 = "Son3";
- {
- System.out.println ("Son common block be called");
- }
- Static {
- System.out.println ("Son static block be called");
- }
- Public Son () {
- System.out.println ("Son constructor be called");
- }
- public static void Main (string[] args) {
- new Son ();
- System.out.println ();
- new Son ();
- }
- }
The content of the son class is basically consistent with the Father class, except that son inherits from father. The class has a main function that is intended for testing purposes only and does not affect the result.
Instantiate son in the main function.
The result is:
[Java]View PlainCopy
- Father static block be called
- Son static block be called
- Father Common block be called
- Father constructor be called
- Son Common block be called
- Son constructor be called
- Father Common block be called
- Father constructor be called
- Son Common block be called
- Son constructor be called
Summarize:
1, executes the static code block of the parent class when the class loads, and executes only once (because the class is loaded only once);
2, executes the static code block of the subclass and executes only once (because the class is loaded only once);
3, the class member of the parent class is initialized and is executed from top to bottom in order of occurrence (as can be seen at debug).
4, executes the constructor of the parent class;
5, class member initialization is performed for subclasses, and is performed from top to bottom in the order in which they appear.
6, executes the constructor of the subclass.
The initialization order of the parent and subclass classes in Java