Java Initializers

In java, we have three types of initializers:

1. Static Initializer:can be used to set the value of any static variables in a class. This is called when the class is loaded into JVM.
2. Instance Initializer:It is used to initialize the instance data members. It runs each time when object of the class is created.The Java compiler copies initializer blocks into every constructor.If the class extends any parent class, then the initializer block content will be copied after super() in the constructor.You can have multiple instance initializer blocks in a class in which case they execute in the sequence in which they appear in the class.
3. Constructor:It is used to initialize the instance data members. It runs each time when object of the class or object of the child class is created.

Let us look into the below example

package com.blog;

public class TestInitializer {

static{// This is static initializer block
System.out.println(“Static Block”);
}

{// This is instance initializer block
System.out.println(“Instance Block”);
}

TestInitializer(){// This is constructor
System.out.println(“Constructor”);
}

public static void main(String[] args) {
TestInitializer testInitializer = new TestInitializer();
}

}

Output:
Static Block
Instance Block
Constructor

Let us look into the contents of the TestInitializer.class file

package com.blog;

import java.io.PrintStream;

public class TestInitializer
{
static
{
System.out.println(“Static Block”);
}

TestInitializer()
{
System.out.println(“Instance Block”);// The contents of the initializer block has been copied here.

System.out.println(“Constructor”);
}

public static void main(String[] args)
{
TestInitializer testInitializer = new TestInitializer();
}
}

When to use Instance Initializers
1. As Java compiler copies initializer blocks into every constructor.Therefore,instance initializers are invoked regardless of which constructor is used for Object creation.This approach can be used to share a block of code between multiple constructors.

2. Instance initializers are also useful in anonymous inner classes, which can’t declare any constructors at all.

Leave a Reply

Your email address will not be published. Required fields are marked *