Java Init Block
Java has two kinds of init code blocks, static init block
and init block
.
-
While
static init block
is used to initialize the class level configurations, and, -
init block
is used to initialize instance data members-
it runs each time when object of the class is created
-
it runs in the order they appear in the program
-
compiler replaces the init block in each constructor after the super() statement
So,
init block
is executed before the constructor logic -
Let's look at the following example,
Java
class IniCodeBlockParent {
static {
System.out.println("parent static block head");
}
{
System.out.println("parent code block before constructor");
}
public IniCodeBlockParent() {
System.out.println("parent constructor");
}
{
System.out.println("parent code block after constructor");
}
static {
System.out.println("parent static block end");
}
}
public class InitCodeBlock extends IniCodeBlockParent {
static {
System.out.println("static block head");
}
{
System.out.println("code block before constructor");
}
public InitCodeBlock() {
System.out.println("constructor");
}
{
System.out.println("code block after constructor");
}
static {
System.out.println("static block end");
}
public static void main(String[] args) {
new InitCodeBlock();
new InitCodeBlock();
}
}
Guess the output of the above program. Or expand to see the results.
Output
Text Only
parent static block head
parent static block end
static block head
static block end
parent code block before constructor
parent code block after constructor
parent constructor
code block before constructor
code block after constructor
constructor
parent code block before constructor
parent code block after constructor
parent constructor
code block before constructor
code block after constructor
constructor