Java object construction process, java object construction
The construction process of an object in Java is as follows:
1-6 belongs to the static initialization part. If the static part of a class has been initialized (it has been loaded by the class loader), the static part will not be initialized again, the static part is initialized only once when the class loader loads a class.
1. Use the class loader to load the parent class, allocate space for all static variables of the parent class according to the sequence defined by the static variables of the parent class, and assign the default value to the static variables of the parent class.
2. Load yourself with a class loader, allocate space for all the static variables in the order defined by the static variables, and assign the default values to the static variables.
3. Assign the defined values to all static variables of the parent class in the sequence defined by the parent class static variables.
4. Execute the static code block of the parent class.
5. Assign the defined values to all static variables in the sequence defined by the user.
6. Execute your own static code block.
7-14 is part of the initialization instance.
7. Allocate space for the parent class instance variables and assign the default value.
8. Allocate space for your instance variables and assign the default value.
9. Assign the defined values to all instance variables of the parent class in the sequence defined by the parent class instance variables.
10. Execute the Construction Code block of the parent class.
11. Execute the constructor of the parent class.
12. Assign the defined values to all your instance variables in the order defined by your instance variables.
13. Execute your own construction code block.
14. Execute your own constructor.
Object Construction complete!
Note:
1. If the parent class has a parent class, the parent class of the parent class will be initialized in this order until the Object ends.
2. if the defined value introduces another class when steps 3, 5, 9, and 12 are executed, the class will be initialized, if the referenced class has a referenced class, the referenced class of the referenced class is initialized in this order until all referenced classes are initialized.
3. If a class does not have a parent class (such as an Object class), the initialization sequence can be simplified to 2, 5, 6, 8, 12, 13, and 14.
4. if this class has been loaded by the class loader, that is, the static part of the class has been initialized, then 1, 2, 3, 4, 5, 6 will not be executed, the overall sequence can be simplified to 7, 8, 9, 10, 11, 12, 13, and 14.
5. if this class is not loaded by the class loader, but its parent class has been loaded by the class loader, the general order can be simplified to 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, and 14.
Please mark the original address for reprinting. Please respect the original address. Thank you.