Question

I have the following doubt about the declaration of a variable as final in Java

If I declare the following variable in my code:

private final String CURRENT_USER;

Eclipse show me the following error message: The blank final field CURRENT_USER may not have been initialized

Why? From what I have understand if I declare a variable as final I can initialize only once but seems to me that I can initialize it only when I declare it and not after somewhere in the code...

Why?

Tnx

Andrea

Était-ce utile?

La solution

You have to initialize it at the declaration or in the constructor.

Either

private final String CURRENT_USER = "SomeUser";

or in the constructor

private final String CURRENT_USER;

public YourClassName(){
   CURRENT_USER = "test";
}

But you should name an instance variable in the camel case way

private final String currentUser;

Otherwise someone (including me) thinks that it is a constant at first sight.

Autres conseils

Java is warning you, because you have created a field; but not initialized the value - therefore, it is implicitly null.

private final String CURRENT_USER; // <-- CURRENT_USER = null;

You can set this constant in every constructor, or you can use a initialization block; for example,

private final String CURRENT_USER;
{
  CURRENT_USER = UserLoader.getCurrentUser(); // <--- load the user.
}

Or using a constructor (again, as an example),

public MyConstructor(String user) {
  CURRENT_USER = user;
}

The JLS says

A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.

And this makes sense for a similar reason to the following

public void someMethod() {
    String s;
    System.out.println(s);
} 

You shouldn't be able to use an un-initialized variable. And since it's final, you can only initialize it once, you have to wait until that initialization happens.

You don't have that many options. Initialize it in an instance initializer block or in the constructor before you use it.

Variables that are declared final must be initialized in the declaration (ie ), a static block or the constructor of the object.

private final String CURRENT_USER = "SOMETHING";

Part of declaring something final is the guarantee that the value will be available to the object once it is fully initialized - otherwise you'll have a final, null object.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top