+ 2

Why is static block not executed even though the class was loaded?

What's exactly happening here? Even though class c was loaded , why did the static block not execute? How is variable y assigned the value from class p and not class c? https://code.sololearn.com/csXIm8KgjgjG/?ref=app

1st Sep 2019, 3:28 AM
Satyam Joshi
Satyam Joshi - avatar
5 Respostas
+ 2
~ swim ~ agreed , but the static blocks are always executed whenever the class is loaded in the memory. Here class c should be loaded in the memory, and if it does , static block must execute. Moreover , if you delete c.class file ,the program will cease to run. That means class c is loaded, and it's required by the program.
1st Sep 2019, 7:30 AM
Satyam Joshi
Satyam Joshi - avatar
+ 1
Since y is a static variable declared in parent class, child class is not initialized, only parent class is initialized. Although if somehow child class was also initialized, y(static variable) 's value won't be changed. It would just print "4" three times.
1st Sep 2019, 5:06 AM
Harin Mehta
Harin Mehta - avatar
0
To conclude , Class c will be loaded but it won't be initialized. So, the compiler converts c.y(in main method) into p.y .
1st Sep 2019, 1:23 PM
Satyam Joshi
Satyam Joshi - avatar