0
Please help me understand the output
I am from C++ and exploring Java now a days. Could any one help me understand output of below code : https://code.sololearn.com/c98QGFgzJ47Z/?ref=app
5 Answers
+ 2
When you access the class for the first time, the static initialization block (3) will run.
When you create an instance of the class, the two instance initialization blocks will run (0 and 2).
Finally the constructor gets called (1).
+ 2
Instance initialization blocks get called just after the super class constructor gets executed. Since the parent class to any class in Java is the Object class, you don't see anything else printed because it has a no-arg constructor generated by the compiler implicitly.
Rest is explained by Manu_1-9-8-5 and I just wanted to add the above set of lines to make it more clear.
Also from the name itself you must understand that an instance initialization block gets called every time an instance of the class is created unlike the static block which is called only once.
https://code.sololearn.com/cukCW7JfVIs5/?ref=app
+ 1
It is used to execute code regardless which constructor is used and to not have to ensure to have a basic constructor to be called from all others.
+ 1
Thanks Manu_1-9-8-5 nd Avinesh
0
What is instance initialisation blocks...afik , it is not there in c++ so I am getting confused... Static block I can understand that with execution of main thread , it initialise some memory even before class constructor is called. What is purpose of instance initialisation blocks...