The above class will give a compile error for an illegal forward reference because we are accessing b before we have defined it. If we change: static int a = b; to static int a = forwardReference(); what will the output be? [ April 15, 2003: Message edited by: Thomas Paul ]
With a = forwardReference(); we will be able to fool the compiler, so it compiles fine. How ever when you run it, when you call forwardReference(), the static variable b has not yet been initialized. So the return b; statement returns the defualt value 0. And that is what gets assigned to a. So the print statement in the main prints TestForward.a as 0.
Does it mean that static method are initialized before static variables?
Charles, methods never get initialized. It is the memeber variables that are intialized using initializer expressions and initializer blocks. Approriate method simply get invoked when there is a call for it in an initializer expressions or initializer blocks. Static initializer expressions and static initializer blocks get executed only once when the class is loaded, in the order they appear in the class. Instance initializer expressions and instance initializer blocks get executed every time a new instance is created, in the order they appear in the class.
Villains always have antidotes. They're funny that way. Here's an antidote disguised as a tiny ad:
a bit of art, as a gift, that will fit in a stocking