Possible Duplicate:
Static Initialization Blocks
Unusual “static” method declaration
I’m trying to prepare for a OCJPC in the near future, and I came across a construct I had never seen before. As it is tough to google for programming constructs, I am asking the question here. The code fragment:
class Geryon {
static { System.out.print("a"); }
{ System.out.print("b"); }
Geryon(String s) { System.out.print(s); }
public static void main(String[] args) {
new Geryon("c");
}
}
I am referring to the 2 print statements inside theGeryon() method header in the place where I would expect a return type. As far as I was able to google, a static method header consists of:
access-modifier keyword-"static" return-type|void method-name
Judging from the answer to the quiz question, the code does not only compile, but will also be run. Can anyone direct me to a source where this is explained?
A is a static initializer that gets called when the class is initialized by classloader, this :
And the other (B) is an anonymous block that gets called every time the class is instantiated :
Oh and the third print statement, C, is just a normal constructor call.
You will get all three lines if you instantiated one Geryon, like the code you posted. But then the next time you instantiated a Geryon you will only get two – B and C; as it has already been initialized by classloader, so the static block does not get called.