class Test {
int a;
void method() {
a = 1;
int a = a = 2;
a = 3;
}
}
There are lots of a
s in method
. What are they all referring to?
class Test {
int a;
void method() {
a = 1;
int a = a = 2;
a = 3;
}
}
There are lots of a
s in method
. What are they all referring to?
Copyright © 2021 Jogjafile Inc.
This is a simple example of the bizarreness of Java's scoping rules.
Breaking it down line-by-line:
a = 1;
is referring to the member variable.a = 3;
is referring to the local variable, because it's after the declaration of the local variable. It's pretty confusing that you can refer to two different symbols via the same identifier, in the same method.int a = a = 2;
: the seconda
is the local variable.The self-reference in the variable declaration is really curious. You can find this in the language spec:
It is also true that member variables can refer to themselves in their own initializer; but this is for a slightly different reason:
I have yet to find a compelling reason for the existence of this rule for local variables; maybe you just really really want to make sure it's assigned. The only thing that I can think it allows you to do is to use the variable as temporary storage in the evaluation of the initializer, for example:
would be equivalent to:
Personally, I'd rather see the second form of the code, as the evaluation of the first just seems obscure.