While researching another question, I was surprised to discover that the following Java code compiles without errors:
public class Clazz {
int var = this.var + 1;
}
In my JDK6, var
gets initialized to 1
.
Does the above code have well-defined semantics, or is its behaviour undefined? If you say it's well-defined, please quote the relevant parts of the JLS.
It is mentioned in passing in the Example 8.3.2.3-1 in section 8.3.2.3. In the text to the example
class Z {
static int peek() { return j; }
static int i = peek();
static int j = 1;
}
class Test {
public static void main(String[] args) {
System.out.println(Z.i);
}
}
the caption says:
... the variable initializer for i uses the class method peek to access the value of the variable j before j has been initialized by its variable initializer, at which point it still has its default value (§4.12.5).
This should map directly to your situation.
Chapter 8.3.2.2. paragraph 2:
Initialization expressions for instance variables are permitted to refer to the current object this (§15.8.3) and to use the keyword super (§15.11.2, §15.12).
Although the next paragraph adds:
Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to instance variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With