This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Forward referencing(was the very informative: Very confused) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Forward referencing(was the very informative: Very confused)" Watch "Forward referencing(was the very informative: Very confused)" New topic
Author

Forward referencing(was the very informative: Very confused)

John Johnson
Ranch Hand

Joined: Nov 05, 2006
Posts: 39
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

Joined: Aug 24, 2005
Posts: 518
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

Joined: Nov 05, 2006
Posts: 39
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

Joined: Nov 22, 2006
Posts: 1
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
 
GeeCON Prague 2014
 
subject: Forward referencing(was the very informative: Very confused)