Iam Tubby wrote:I would like some clarification on why the first is legal reference and the second illegal reference.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Winston Gutkowski wrote:
The "first pass" creates the space for the two variables and establishes their names.
The second pass establishes
1. The method, which can now access j (which at this point has a value of 0).
2. Sets i to the result of test();
3. Sets j to 5.
I hate to say, but it's something you'll probably never have to deal with (and certainly not if you write your classes properly). So I'd say it comes under the heading of DontSweatIt.
Is there any particular reason you think it might be important?
Shubham Semwal wrote:
What you are doing here is forward reference i.e using an identifier before its declaration. Based on situation it will either result in an error, warning or return with default values(as in this code).
It is logically wrong and hence the value being returned by test() is default value.
Rico Felix wrote:The reason that the following is illegal is because of the order of initialization from the compiler
Static and instance variables within the declaration of a class are initialized to their default values in their order of declaration ... In the above code i is trying to copy the value from j which has not yet been initialized since it was declared after i
Iam Tubby wrote:
Rico Felix wrote:The reason that the following is illegal is because of the order of initialization from the compiler
Static and instance variables within the declaration of a class are initialized to their default values in their order of declaration ... In the above code i is trying to copy the value from j which has not yet been initialized since it was declared after i
Thanks for the reply Rico. I understand, but why is initialization allowed from a method, even if variables are not initialized in the order of declaration. As in, how are we able to access j before i in spite of j being initialized after i.(refer snippet below)
Thanks for the reply Shubham. If it is logically wrong, then why does Java support this kinda initialization ?
Wouldn't it have been much better if variable initialization was achieved only if variables appeared in the correct textual order, as in, no legal forward referencing at all.
Rico Felix wrote:
The variable declarations may be scattered throughout and in between method definitions, but the variables are initialized before any methods can be called.
Shubham Semwal wrote:
compiler is a set of codes .. it can't check logic.
There is no way for the program to make an optimized variable textual order.