In other words, why would you need an instance initializer? What difference or advantage do you have in writing a instance initializer over a constructor?
相关问题
- 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
In terms of object lifecycle, there is no difference. Both are invoked at construction time, and logically the initializer block can be considered part of construction.
Semantically, an initializer is a nice tool to have for several reasons:
the initializer can improve code readability by keeping the initialization logic next to the variable being initialized:
vs
Initializers are invoked regardless of which constructor is used.
Initializers can be used in anonymous inner classes, where constructors can't.
The real advantage of instance initializers over constructors is seen when we use an anonymous inner class.
Anonymous inner classes can't have a constructor (as they're anonymous), so they're a pretty natural fit for instance initializers.
I would avoid the instance initializer idiom in general - the only real advantage it gives over variable initializers is exception handling.
And since an init method (callable from constructor) can also do exception handling and also centralizes constructor setup code, but has the advantage that it can operate on constructor parameter values, I'd say that the instance initializer is redundant, and therefore to be avoided.
Initializer is way to share code between constructors and it make code more readable if initializer is used with variable declaration.
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors. Oracle documentation
When you have many constructors and want some common code to be executed for each constructor you can use instance initializer.As it is called for all constructors.
This seems to explain it well:
From: JavaWorld Object initialization in Java.