Tuesday, January 16, 2018

Static Block Vs Instance Block In Java

These two have two different advantages:

•The static initializer block will be called only once on while loading the class, and will have no access to instance variables or methods. It is often used to create static variables.

•The non-static or Instance initializer block on the other hand is called on object construction only, will have access to instance variables and methods, and will be called at the beginning of the constructor, after the super constructor has been called before any other subsequent constructor code is called. I've seen it used when a class has multiple constructors and needs the same initialization code called for all constructors. Just as with constructors, you should avoid calling non-final methods in this block.

•Instance Initializer block will be called very time when object creation.

The Instance Initializer block:

{
    // Statements...
}

This will be called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

public class TestBlock {

    static{
        System.out.println("Static Block");
    }

    {
        System.out.println("Initializer block");
    }

    public static void main(String[] args) {
        TestBlock t = new TestBlock();
        TestBlock t2 = new TestBlock();
    }
}

Output:

Static Block
Initializer block
Initializer block

No comments: