Skyop22
Skyop22

Reputation: 15

Can I define a final variable with another final?

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

Upvotes: 1

Views: 65

Answers (5)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

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.

Upvotes: 1

tony
tony

Reputation: 88

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"

Upvotes: 0

John3136
John3136

Reputation: 29266

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

Upvotes: 3

Jonathon Anderson
Jonathon Anderson

Reputation: 1200

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

Upvotes: 0

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32478

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;

Upvotes: 3

Related Questions