ankur said:
I sure am missing something very simple here. This simple piece of
code compiles without error :
[ Reformatting for readability. ]
public class SampleClass {
int j = 10*this.r;
int r;
}
But this does not:
public class SampleClass {
int j = 10*r;
int r;
}
Section §8.3.2.3:
The declaration of a member needs to appear textually before it is used
only if the member is an instance (respectively static) field of a class
or interface C and all of the following conditions hold:
* The usage occurs in an instance (respectively static) variable
initializer of C or in an instance (respectively static) initializer of C..
* The usage is not on the left hand side of an assignment.
* The usage is via a simple name.
* C is the innermost class or interface enclosing the usage.
What this means is that if we want to use a forward reference, we have
to ensure that we break one of those requirements. Here our are options:
Option 1: Forward references are permissible in constructor bodies.
Option 2: Forward references are permissible on the lhs of an assignment
(e.g. int j = r = 10) [1].
Option 3: Forward references are permissible if you do it via a
qualified name (e.g., int j = this.r * 10).
Option 4: Forward references are permissible within inner classes.
The first class does option 3, but the second class uses none of them.
[1] Pop quiz! Does this compile? Justify your answer with citations from
the JLS.
class Test {
int j = (r = 10) + 1;
int k = r++
int r;
}