File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Forward Referencing, Initializers 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, Initializers" Watch "Forward Referencing, Initializers" New topic

Forward Referencing, Initializers

Dirk Hudson

Joined: Oct 14, 2004
Posts: 1

when i compile the above code I get a illegal forward reference error on line 5.
so i changed the reference to this.width which seems to work with 0 as default value
of width.

what is going on here ? isn't width and this.width the same thing ?

i have a guess that all instance variables are assigned their default values when
a class is loaded (ie when static vars are initialized) and are then "explicitly"
initilized when an instance is created using new. this theory seems to be accurate as
when I did the following:

i get a "cannot resolve symbol" error.

Edited by Corey McGlone: Added CODE Tags
[ October 14, 2004: Message edited by: Corey McGlone ]
Colin Fletcher
Ranch Hand

Joined: Sep 10, 2004
Posts: 200
Dirk, The problem with the below code is this...
length is defined as 10 - ok
System.out.println ... On this line you are trying to use the width variable, but the width variable is not declared BEFORE you use it. The compiler complains and says there is a forward reference which means you use the variable before defining the type / value for it. Moving the declartion to before the "System.out.println..." will correct this.

Another way to think of it is this: (be the compiler) How can I print the value of the width variable when I don't even know what type it is ?

SCJP 1.4 SCWCD 1.4
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
In general, the compiler will prevent you from reading a variable that has not yet been initialized. However, there are ways to "trick" the compiler into allowing you to do so. The trick I use most often is this:

By invoking a method that gets me the value of b, the compiler doesn't realize that we're referencing a variable that hasn't yet been initialized. Basically, the compiler just isn't that smart. By using the keyword "this", you're accomplishing the same thing - you're tricking the compiler into allowing you to do something you should not be doing.

SCJP Tipline, etc.
I agree. Here's the link:
subject: Forward Referencing, Initializers
It's not a secret anymore!