1

This is more of a hypothetical question but if I have some final called A and another final B that are both ints, I can't do this:

private final int A = B/2, B = (some kind of other derived number);

I am just wondering why. Any help would be awesome. NetBeans popped up an error on this and I just want to know why it is a problem.

PS-The error that popped up said "illegal forward reference".

Skyop22
  • 15
  • 1
  • 4

5 Answers5

3

You are accessing variable B before you declare it. That's the reason for "illegal forward reference".

Define variable B before A

private final int B = (some kind of other derived number), A = B/2;
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
3

Pretend you're the compiler:

private final int ok. Mr user wants a "const" int

A the variable is called A

= ...here comes the value

B/2 HUH? WHAT THE HELL IS B? NO ONE TOLD ME ANYTHING ABOUT B. STUFF YOU USER. I'M OUT OF HERE...

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
John3136
  • 28,809
  • 4
  • 51
  • 69
1

The existing answers don't answer the underlying question:

Why can I use methods that are defined later in my source file, but does the same with variables cause a forward reference error message?

The answer is found in the JLS, more specifically JLS $12.4.1

The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

This question was answered here. Basically it means that you are trying to use a variable that is not initiated.

Initialize B first, then use it to initialize A

private final int B = ?, A = B/2;

illegal forward reference in java

Community
  • 1
  • 1
Jonathon Anderson
  • 1,162
  • 1
  • 8
  • 24
0

Your code isn't failing because A and B are final. It's failing because B isn't declared/initialized yet. If you declare it first, you'll be able to use them just fine.

For example,

private final int C = 5;
private final int B = C/3;
private final int A = B/2;

This is fine because B is declared first :)

"final" just means that you can't change the variable. So something like this won't work

private final static int C = 5;
private final static int B = C/3;
private final static int A = B/2;

public static void main (String[] args) {
    A = 5;
}

because now we're trying to modify A which is "final"

tony
  • 88
  • 8