class Bird { { System.out.print("b1 "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); new Hawk(); System.out.println("hawk "); } }
What is sequence of execution of statement ? memory allocation ?
The code uses static and instance init blocks. Static init blocks are executed only once the first time the class is loaded. Instance init blocks are executed every time a new instance of the class (object) is created, just after the call to super() from any subclasses constructors. Based on that fact, we can see that when the program is run, the class Hawk is loaded, as its super class Raptor, and the super-super class Bird. In the case of Raptor, there are two static init blocks, and they are executed in the order in which they appear in the class file. So, output begins with: r1 r4
There are no other static init blocks so the next thing that happens is back in the main method where we have the:
r1 r4 Pre
Next, we create an instance of our Hawk class. When this object is created, the non-static init blocks are executed. They are executed just after the call to the super() constructor, so the first one that will be executed is in the top of the object tree, and we get b1, and the the super-super constructor runs and we get b2.
r1 r4 Pre b1 b2
In the Raptor class, the non static-init block runs followed by the constructor in the Raptor class runs, so we get r3 r2. Finally, we end with the System.out.println in the last section that displays "hawk ".
The final result is:
r1 r4 Pre b1 b2 r3 r2 hawk
what are the instance init block.? can you give me an example illustrating when the init block are called every time the new instance of the class is created. instance is something like if demo is a class demo d1 or new demo(). Thank you .
Ads