Initialization order of java classes

Article reprint https://www.cnblogs.com/wenruo/articles/5349525.html

one. Without considering the parent class, when creating an object of a class, first initialize static variables and static code blocks (the initialization order of static variables and static code blocks is in the order in the class), and then initialize non-static variables and static code blocks. Non-static code blocks (non-static variables and non-static code blocks are also in the order in the class), if the non-static variable does not display assignment, it will be assigned the default value. Finally execute the constructor. Static members are only initialized once, so they will not be executed again after they have been initialized.

two. Static member variables and static code blocks will not only be initialized when the object is initialized, but all static members will be initialized when the static variable or static function is referenced for the first time.

three. Then consider the case of having a parent class. When the static field of the subclass is initialized, the static field of the superclass must be initialized first. Therefore, when the static variable or function of the parent class is referenced for the first time, the static field of the parent class will be initialized.

When a subclass object is created, the static fields will be initialized first (if they have not been initialized before), the static fields of the parent class will be initialized first, and then the static fields of the subclass will be initialized. After that, the non-static fields and constructors of the parent class will be initialized, and then the subclass's.

For more examples, please refer to: https://www.cnblogs.com/wenruo/articles/5349525.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324533622&siteId=291194637