Forums Register Login

Forward Referencing, Initializers

+Pie Number of slices to send: Send


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 ]
+Pie Number of slices to send: Send
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 ?

+Pie Number of slices to send: Send
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.
What does a metric clock look like? I bet it is nothing like this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 787 times.
Similar Threads
Static Blocks and Instance Initializers (on certification exam?)
Instantiation/Forward referencing
when static variables are initialized
help with blank final variables
Instantiation/Forward referencing
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:16:57.