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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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
First of all, there are two types of initialization blocks:
This code should illustrate the use of them and in which order they are executed:
Prints:
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.
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.