• Post Reply Bookmark Topic Watch Topic
  • New Topic

static block weird case  RSS feed

 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a weird case in static block initialization with a static variable. It seems you can put the static block before the declaration, since the following code works! but why?



To make things more weird, the following code won't work! You can't refer the static variable. Error message: "illegal forward reference". Why?

 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is explained in the JLS here. Basically, you can use a variable in an initializer block before it's declared in only one way: as the left-hand-side of an assignment statement.
 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. It is really tricky.
 
Warren Dew
blacksmith
Ranch Hand
Posts: 1332
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest, any idea why that restriction exists? Seems like it shouldn't be so difficult for the compiler to figure out....
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's nominally to prevent cycles in initializers. If this restriction didn't exist, then



would be legal. It's illegal only because "j" is used somewhere besides on the left-hand-side of an assignment in the static block.
 
David Hibbs
Ranch Hand
Posts: 374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even more confusing to many is this case:


Running a program and accessing i reveals that i is zero!

Initializers are executed in the order present in the source file, effectively resulting in the block

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!