4

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!

Community
  • 1
  • 1
user3780616
  • 1,183
  • 1
  • 10
  • 23
  • what error does eclipse give? I cut and pasted your example into IntelliJ, and it was happy. – Chris K Jul 02 '14 at 16:25
  • It gives the second code block in my post above. I'm using 4.4.0 and Java 7 but the actual error when I run it is this: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The blank final field myString may not have been initialized at package.(A.java:31) at package.Test.main(Test.java:5)initialized – user3780616 Jul 02 '14 at 16:27
  • As an aside, I would suggest using the convention of upper-case with underscores for naming constants `LIKE_THIS`. – Tripp Kinetics Jul 02 '14 at 16:29
  • Does it work if you simply call `javac` on the file? It's a longshot. – Tripp Kinetics Jul 02 '14 at 16:29
  • In your real code, do you have more than one constructor? Or have you seen this problem with the exact code above. I suspect that something is being lost in translation. – Chris K Jul 02 '14 at 16:31
  • Interesting discussion here: [compile - Java "blank final field may not have been initialized"](http://stackoverflow.com/questions/5652772/java-blank-final-field-may-not-have-been-initialized-exception-thrown-in-metho). See also [Java the final field may not have been initialzied](http://stackoverflow.com/questions/14599721/the-final-field-may-not-already-have-been-initialized) – FoggyDay Jul 02 '14 at 16:32
  • 2
    @user3780616 I doubt that the code above produces this error. Please provide the full example (your class A does not have a line #31) – isnot2bad Jul 02 '14 at 16:32

1 Answers1

5

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.

  • Reinstalled JDK and Eclipse and everything works. Not sure why, but hey, it works :) Thanks for the help everybody! – user3780616 Jul 02 '14 at 16:41