This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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 ]
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 ?
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.