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;
}
Illegal forward reference
Moderator: admin
-
- Posts: 31
- Joined: Thu Feb 19, 2015 8:25 am
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Illegal forward reference
What error message did you get when you tried to compile it?
Also, please include the question id of the question.
thank you,
Paul.
Also, please include the question id of the question.
thank you,
Paul.
-
- Posts: 31
- Joined: Thu Feb 19, 2015 8:25 am
- Contact:
Re: Illegal forward reference
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.
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.
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Illegal forward reference
This is just one of the many rules of Java language. As per section 8.7 of the Java Language Specification:
and section 8.3.2.3
HTH,
Paul.
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
The one that I have highlighted above is why your second code example doesn't compile.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.
HTH,
Paul.
Who is online
Users browsing this forum: No registered users and 10 guests