简体   繁体   中英

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

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;

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

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.

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM