Class and Instance Initializers

Class and instance initializers are blocks of code outside constructors or methods. A class can have any number of initializers. They can be anywhere in the class body and are called in the order that they appear in the source code.

Class initializers (also called static initialization blocks) use the static reserved word. Java invokes these blocks when the class is loaded:

Instance initializers (also called initializer blocks) are even simpler. The Java compiler copies these blocks into every constructor (at the beginning). That’s why they are also called shared code.

Field Initialization

Fields have a default value so if you don’t initially assign a value to them, they get initialized with that default value. That being said, you must be careful about final instance variables (non-static fields): they must be initialized when an instance is constructed, or code will not compile. This can be done either in an instance initializer or in every constructor.

Initialization Flow

What’s the initialization flow of initializers and constructors when you create an instance of a class that has a superclass? Trust me: the answer to this question is something you must know before trying the exam.

The order of calls is the following:

  1. Static blocks* of the superclass
  2. Static blocks* of the class
  3. Non-static blocks* of the superclass
  4. Constructor of the superclass
  5. Non-static blocks* of the class
  6. Constructor of the class

 

I use the following 3 to easily remember the previous 6:

Initialization of an object of class B extending class A
1. Everything static in order A ↓  →  B ↓
2. Create A instance {...}  →  A()
3. Create B instance {...}  →  B()

Leave a Reply