Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Forward referencing(was the very informative: Very confused)

 
John Johnson
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm very confused with forward referencing. Why I cannot do this

But I can do this

This gives output 0, which I also don't understand. Please help!
[ November 23, 2006: Message edited by: Barry Gaunt ]
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first example, the compiler is confused as to what 'a' variable you are referring to. It thinks you are referring to a local variable, but no local variable 'a' has been defined yet. This is the same behavior you would see if this code was inside a method.

You can make this code work by being explicit about what 'a' you are referencing:



In the second example, the method doIt() has not defined a local variable 'a' but the method has visibility to the class-level fields. So the compiler assumes you are referencing the 'a' at the class-level.

doIt() executes when the class is loaded because it's called from a class-level static block. It returns 0 because the code to initialize 'a' has not been executed yet when doIt() is called and 0 is the default value for an int.
[ November 23, 2006: Message edited by: Scott Johnson ]
 
John Johnson
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Scot.
I still don't understand. How come the method has visibility to the variable but initialization block doesnt? Also, when I write

The code compiles normally? Why does the order matter?
 
Uma Jaladi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Johnson:
Hi Scot.
I still don't understand. How come the method has visibility to the variable but initialization block doesnt? Also, when I write

The code compiles normally? Why does the order matter?

-------------------------------------------------------
Hi,

See the following!!!


Restrictions on the use of Fields during Initialization
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic