can anyone explain me the output? i mean the order......i think first superclass static block will run then its constructor and then the subclass's static block and then its constructor....but out put comes different
is there any good link that explains the order of execution
ankur kothari wrote:output is: Ankur2
but i was expecting Ankur2(static block)
Static blocks runs first and only then constructors are called.
Static blocks run only once when classes are first loaded.As class Test8 extends class Test7 both will be loaded as such their static blocks run first.After that constructors run.If I'm wrong please somebody correct me.
Ststic block runs when the class is loaded and non static block runs after every call to super constructor.
here is the order how it iwll run.
When the class is loaded JVM will check if there is any super class for it,if so it will load the super class also and this continues until the Object class and then it will execute the static block in the declared order from the upper tree till the sub class that is getting loaded.
Once this is done main method will run and then if the instance of the subclass is created then its constructor will run which calls super constructor and this continues until Object class then it will execute any non instance initalizer or initializer block in the declared order till the sub class contructor.
Note: Instance initializer block will get executed only after call to super constructor not for every constructor.
To put it in simple word.Instance initializer block will run for the constructor that has call to super.
In the abve code instance block runs will be displayed only once as the call to super is present only in one constructor.