What is an initialization block?

后端 未结 10 2134
青春惊慌失措
青春惊慌失措 2020-11-22 03:42

We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?

10条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 04:05

    would like to add to @aioobe's answer

    Order of execution:

    1. static initialization blocks of super classes

    2. static initialization blocks of the class

    3. instance initialization blocks of super classes

    4. constructors of super classes

    5. instance initialization blocks of the class

    6. constructor of the class.

    A couple of additional points to keep in mind (point 1 is reiteration of @aioobe's answer):

    1. The code in static initialization block will be executed at class load time (and yes, that means only once per class load), before any instances of the class are constructed and before any static methods are called.

    2. The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed exactly before the code in constructor.

提交回复
热议问题