Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Initializer Block

 
Sherry Jacob
Ranch Hand
Posts: 128
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was going thru Static Initializer Block topic in the Khalid Mughal book.
The book mentions a small example 2 depict illegal forward referencing.



The theory states that there is an illegal forward referencing at (4) where an attempt is made to read the value of field sf1 before it is declared ?

Howz that so ? It's been declared at (1).
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line 1 is not a declaration, which would look like

int sf1 = 20;

It's an assignment. And of course, variables declared inside a static initializer block -- or any block -- are local to that block; so if line 1 were a declaration, then this discussion of static variable initialization would be irrelevant.
 
Layne Lund
Ranch Hand
Posts: 3061
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As EFH points out, there is something missing in your post. You should look for something like

private static int sf1;

further down in the code listing. This is the declaration NOT line (1).

As a review, all variable declarations must contain the type of the variable. Instance variables also contain an optional access modifier (private, protected, or public) and an optional "final" specifier. Class variable declarations also contain the keyword "static". Declarations can also contain an = and a value to initialize the variable. However, without the type specifier, an = alone is just an assignment operation not a declaration.

I apologize for babbling on. I hope this clarifies the differences between declaration, initialization, and assignment. If not, please post your concerns or review your textbook for futher information.

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic