Illegal forward reference

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Sergiy Romankov
Posts: 31
Joined: Thu Feb 19, 2015 8:25 am
Contact:

Illegal forward reference

Post 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;
}

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Illegal forward reference

Post 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.

Sergiy Romankov
Posts: 31
Joined: Thu Feb 19, 2015 8:25 am
Contact:

Re: Illegal forward reference

Post 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.

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Illegal forward reference

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests