Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using this.var during var's initialization [duplicate]

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.

like image 567
NPE Avatar asked Apr 05 '13 08:04

NPE


2 Answers

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.

like image 65
Keppil Avatar answered Sep 21 '22 22:09

Keppil


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.

like image 36
Matej 'Yin' Gagyi Avatar answered Sep 22 '22 22:09

Matej 'Yin' Gagyi