Page 1 of 1
Illegal forward reference
Posted: Mon Jan 25, 2016 2:15 pm
by Sergiy Romankov
Hallo, could you please explain Why it is so?
class Sattelite{
static {
var = 10; // is OK
}
static final int var;
}
public class Moon {
static {
++var; //ERROR
}
static int var;
}
Re: Illegal forward reference
Posted: Mon Jan 25, 2016 9:57 pm
by admin
What error message did you get when you tried to compile it?
Also, please include the question id of the question.
thank you,
Paul.
Re: Illegal forward reference
Posted: Tue Jan 26, 2016 6:52 am
by Sergiy Romankov
I get compilation error and eclipse says that I can
not reference a field before it is defined?
But in first option it is OK.
This question is not from enthuraQuestions, I just tried
deffirent options and don`t understand why it is so.
I hope that is not wrong to ask so.
Thanks.
Re: Illegal forward reference
Posted: Tue Jan 26, 2016 10:54 am
by admin
This is just one of the many rules of Java language. As per section 8.7 of the Java Language Specification:
Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope.
and section 8.3.2.3
8.3.2.3. Restrictions on the use of Fields during Initialization
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.
It is a compile-time error if any of the four requirements above are not met.
The one that I have highlighted above is why your second code example doesn't compile.
HTH,
Paul.