yen hoang wrote:Pleaon explain for me why the assign a certain value to a variable in instance initialization block is ok but increment ( or st like that) is not
JLS (§8.3.2.3) has this to say :
The declaration of a member needs to appear 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:
1. The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
2. The usage is not on the left hand side of an assignment.
3. C is the innermost class or interface enclosing the usage.
By incrementing (
y++) which is equivalent to (
y = y+1) , you implicitly used y at the right side of an assignment. Just IMHO though :-)
Interestingly, if you change
y to
static int in your declaration, the compiler will not complain anymore

See JLS (§8.3.2.2 )