What is the sense of "Instance Initializers" in Java ?
Can't we just put that block of code at the beginning of the constructor instead?
Instance initializer block works are used to initialize the properties of an object. It is invoked before the constructor is invoked. It is invoked every time an object is created.
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. The initialization of the instance variable can be done directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
Initializer block : contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class. Constructors : are used to initialize the object's state.
In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created.
I use them very often, typically for creating and populating Map in one statement (rather than using an ugly static block):
private static final Map<String, String> CODES = new HashMap<String, String>() { { put("A", "Alpha"); put("B", "Bravo"); } };
One interesting and useful embellishment to this is creating an unmodifiable map in one statement:
private static final Map<String, String> CODES = Collections.unmodifiableMap(new HashMap<String, String>() { { put("A", "Alpha"); put("B", "Bravo"); } });
Way neater than using static blocks and dealing with singular assignments to final etc.
And another tip: don't be afraid to create methods too that simplify your instance block:
private static final Map<String, String> CODES = new HashMap<String, String>() { { put("Alpha"); put("Bravo"); } void put(String code) { put(code.substring(0, 1), code); } };
You could indeed put the code at the beginning of every constructor. However, that's precisely the point of an instance initializer: its code is applied to all constructors, which can be handy if you have many constructors and a bit of code that is common to all of them.
(If you're just starting out with programming, you might not have known that it is possible to create many constructors for the same class (as long as they take different parameters); this is known as constructor overloading. If you only have one constructor, then an instance initializer is indeed not very useful (Edit: Unless you abuse it in creative fashions, as illustrated in the other answers).)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With