It has to do with the order in which in which a new instance gets created. The order is (roughly) as follows:
1. Memory is allocated for the object
2. Instance variables are initialized to their default values (in this case, i and j are initialized to 0 because that's the default for ints)
3. Constructor hierarchy is invoked for all parent objects (in this case, none)
4. Execute instance initializers (this is where i gets assigned to the result of giveMeJ() -- which returns 0 because j is still 0 -- and j gets assigned to 10)
5. Execute the rest of the constructor body
Of course, the order of the initialization matters (illegal forward referencing). For example, on my machine, the following code yields:
0
10
10
But since j *is* initialized to 0 before the method call, you won't get the illegal forward referencing error.
For more info, see section 12.5 of the JLS.
http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.5 See also this explanation of
object initialization. The whole article is pretty good.
EDIT: Fixing code example, and added additional link.
[ August 18, 2005: Message edited by: Ryan Kade ]
[ August 18, 2005: Message edited by: Ryan Kade ]
[ August 18, 2005: Message edited by: Ryan Kade ]