What is an initialization block?

后端 未结 10 1844
青春惊慌失措
青春惊慌失措 2020-11-22 03:42

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?

10条回答
  •  隐瞒了意图╮
    2020-11-22 04:09

    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.

提交回复
热议问题