Reputation: 1982
Here is my code snippet where I'am taking confidence with initialization blocks
class Father{
Father() {
System.out.println("Father constructor runs...");
}
static {System.out.println("static init block of Father...");}
{System.out.println("instance init block of Father...");}
}
class Child extends Father {
Child () {
System.out.println("Child constructor runs...");
}
static {System.out.println("static init block of Child ...");}
{System.out.println("instance init block of Child ...");}
public static void main (String[] argv) {
new Child();
}
}
The two classes are compiled into a single class file: Child.class I run it with command line java Child
this is my ouput:
static init block of Father...
static init block of Child ...
static init block of Child ...
instance init block of Father...
Father constructor runs...
instance init block of Child ...
Child constructor runs...
I'am fine with this output except the fact that "static init block of Child ..." is printed twice. From java documentation i read "Static init blocks run ONCE, when the class is first loaded".
So does this mean that my class Child is loaded twice??
Any help is appreciated Thanks Alberto
Upvotes: 1
Views: 298
Reputation: 1503090
Unable to reproduce - here's the output I get from your code by running it from the command line:
static init block of Father...
static init block of Child ...
instance init block of Father...
Father constructor runs...
instance init block of Child ...
Child constructor runs...
You haven't said how you're running the code, but I suspect that either the output isn't really what you think it is, or you're running it in some odd way.
Your expectation is correct: the static initializer blocks should only be run once.
Upvotes: 2