Search code examples
javaconstructorfinal

Initialize final variable in constructor


I'm trying to initialize a private final variable in the constructor of my class. I found this thread explaining how to do it (Initialize a static final field in the constructor), but eclipse doesn't seem to like my code. I was wondering if someone could shed some light on what I might be doing wrong.

public class A {
  final private String myString;

  public A() {
    myString = "content";
  }
}

With this code I'm getting:

The blank final field myString may not have been initialized

This seems pretty dang similar to the examples in the thread I linked to.

Thank you for the help!


Solution

  • Your code is perfectly valid. This is probably caused by:

    1. Bad IDE settings
    2. Damaged or alternative javac compiler.

    Re-download your IDE, you probably want to download the latest version of it and perform a clean install. You can also try to download and install JDK again (preferably latest version).

    Just a little tip. In Java, there is a convention that variable visibility modifier comes first. So instead of final private, learn to write private final.