Cham Wick wrote:Please refer the following class
I added some Strings for identification. When it creats the object....
Please some one explain me what happens then?
Why it doesn't fail in giveMeJ() method?
when i is initialized , it will be assigned default value of j which is 0. the program you wrote is a way to override compiler protection of forward referencing a variable. refer to JLS section
http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.3.2.3. it says that
The declaration of a member needs to appear textually 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:
• The usage occurs in an instance (respectively static) variable initializer of C
or in an instance (respectively static) initializer of C.
• The usage is not on the left hand side of an assignment.
• The usage is via a simple name.
• C is the innermost class or interface enclosing the usage.
A compile-time error occurs if any of the four requirements above are not
met.
This means that a compile-time error results from the test program:
class Test {
int i = j;// compile-time error: incorrect forward reference
int j = 1;
}