Initialization block in JAVA
An initialization block is a block of code between braces that is executed before the object of the class is created. As the execution of the initialization block is dependent on the creation of the object we can easily make a guess that it has two types of object.
1. Non static initialization block.
It is dependent on the object and the initialization block is executed for each object of the class that is created. It can initialize instance member variables of the class. Here is a simple example.2. Static initialization block.
It is defined using the keyword static and is executed once when the class is loaded and has a restriction that it can only initialize static data members of the class.The only difference between both the samples above is with the two static keywords added and you can definitely see difference in the output. One outputs different values for two objects created and other one the same values.
You can have multiple initialization blocks in a class in which case they execute in the sequence in which they appear in the class.
Note that any initialization block present in the class is executed before the constructor.
So now the question comes why we need constructors if we have initialization blocks. The answer is we don't need the default constructor but initialization block cannot be parameterized and so you cannot have objects taking values from out side and so initialization block is not a substitute for constructor.
Re: Initialization block in JAVA
Thanks shabbir . very helpful
|All times are GMT +5.5. The time now is 09:03.|