Hi. There's an exercise question In head first java where you have to predict the output of a program. According to the answer , It seems like the static Initializer Is inherited from the parent class.
Is that the case ?
output: %java StaticTests
super static block
static block 3
You cannot do StaticSuper on line 05.
Anonymous code block cannot be named.
It can be eather static or regular (no static).
When you run the code:
1. Static anon block in StaticSuper (line 02) executed to be kept before main starts.
2. Static rand created(line 11).
3. Static anon block in StaticTests(12) executed to be kept before main starts.
4. main starts (line 19)
5. If you delete StaticSuper word at line 05, anon code block will be running for superclass (line 05).
6. constructor StaticTests() executed and new instance returned to main at line 21.
Nikolas Nikolaou wrote:
If StaticSuper Is not Inherited , why does It run If the static main method Is In a different class ?
Instances of StaticTests classes IS-A instances of StaticSuper, so instantiating them will require constructors of the StaticSuper class to run as well. Not sure how you concluded that it is related to inheritence -- it's invocation is merely part of the initialization process, when the instance was created at line 21.
Nikolas Nikolaou wrote:Thanks for the reply.What I meant to say was why does the static Initializer of StaticSuper run before the main() method In the other class according to the output.
First, I never confirmed / checked where (or if) it is mentioned in the JLS -- so take this answer with a grain of salt.
It seems that before any static method is called, the class (along with its super classes) must be loaded first. And loading of the class (and superclass) files will trigger the execution of the static initializers. This is probably also true for instance methods, but those classes are loaded when the object is instantiated, so calling the method doesn't trigger any new class files to be loaded.
On loading a class the JVM will ensure its parent class is loaded, and then prepared.
It's the Preparation stage that creates any static attributes, and runs any static initialisers.
So, in the example above, the JVM will load StaticTests, see it has a dependency on StaticSuper, so loads that and so the static code is executed...all before the main() is run.