What is an initialization block?

2020-01-22 11:20发布

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?

9条回答
【Aperson】
2楼-- · 2020-01-22 12:17

Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. It is not at all necessary to include them in your classes.

They are typically used to initialize reference variables. This page gives a good explanation

查看更多
forever°为你锁心
3楼-- · 2020-01-22 12:20

First of all, there are two types of initialization blocks:

  • instance initialization blocks, and
  • static initialization blocks.

This code should illustrate the use of them and in which order they are executed:

public class Test {

    static int staticVariable;
    int nonStaticVariable;        

    // Static initialization block:
    // Runs once (when the class is initialized)
    static {
        System.out.println("Static initalization.");
        staticVariable = 5;
    }

    // Instance initialization block:
    // Runs each time you instantiate an object
    {
        System.out.println("Instance initialization.");
        nonStaticVariable = 7;
    }

    public Test() {
        System.out.println("Constructor.");
    }

    public static void main(String[] args) {
        new Test();
        new Test();
    }
}

Prints:

Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.

Instance itialization blocks are useful if you want to have some code run regardless of which constructor is used or if you want to do some instance initialization for anonymous classes.

查看更多
看我几分像从前
4楼-- · 2020-01-22 12:21

Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialise the common part of various constructors of a class.

The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor.

What if we want to execute some code once for all objects of a class?

We use Static Block in Java.

查看更多
登录 后发表回答